PageSourceSearch

https://hashtelegraph.com/assets/ImportPage-D6WGZAGC.js

js hashtelegraph.com collected 2026-10-02 04:49:27 UTC 19,345 bytes, 2 lines download raw bytes

1import{y as K,r as o,j as e,s as $}from"./index-DmLZxq8s.js";import{u as ue}from"./AuthContext-BcT2tnas.js";import{B as I}from"./button-DlN1-myb.js";import{I as re}from"./input-C9ZZrsMv.js";import{P as ae,U as G}from"./progress-D3ARteZp.js";import{S as xe}from"./switch-DKcQm4TQ.js";import{L as Q}from"./label-BNUu6UY6.js";import{U as he}from"./users-DFjd3hfX.js";import{L as S}from"./loader-circle-BJyDwyFM.js";import{C as ne,I as pe}from"./image-wodsvdlc.js";import{N as fe}from"./ClientRouterApp-DT0cPHEi.js";import{R as ge}from"./refresh-cw-B3KPOC8h.js";import{D as ee}from"./download-C8EzxRKR.js";import{S as se}from"./send-DDnizw5q.js";import"./index-ybg0bLXR.js";import"./index-DF4uq1mV.js";import"./index-Ces_nxI-.js";const P=K("CircleCheckBig",[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]]);const oe=K("Play",[["polygon",{points:"6 3 20 12 6 21 6 3",key:"1oa8hb"}]]);const le=K("Square",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]]),te="Алексей Алоисов",W="guest-authors-backfill-tick-lease",be=25e3,Z=1e4,je=3e4;function Ne(){const[a,q]=o.useState(null),[t,T]=o.useState(!1),[j,C]=o.useState(!0),[A,H]=o.useState(te),N=o.useRef(null),E=o.useRef(!1),h=o.useRef(!0),w=async(s,n)=>{const{data:{session:v}}=await $.auth.getSession();if(!v?.access_token)throw new Error("Not authenticated");const u=await fetch("/supabase/functions/v1/backfill-guest-authors",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${v.access_token}`,apikey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Imhid3B3eHlwdmtuY3l2dnVlcWtmIiwicm9sZSI6ImFub24iLCJpYXQiOjE3ODM0ODA3ODAsImV4cCI6MjA5OTA1Njc4MH0.EobqTstpDfZAkM_3b3hkx_1ycMusd5BugnvCzcujxhE"},body:JSON.stringify({action:s,...n??{}})});if(!u.ok){const D=new Error(`HTTP ${u.status}: ${await u.text()}`);throw D.status=u.status,D}return u.json()},B=()=>{const s=Date.now(),n=Number(localStorage.getItem(W)||"0");return n&&s-n<be?!1:(localStorage.setItem(W,String(s)),!0)},F=()=>{localStorage.removeItem(W)},l=async()=>{try{const{data:s,error:n}=await $.from("guest_author_backfill_jobs").select("*").order("started_at",{ascending:!1}).limit(1).maybeSingle();if(n)throw n;return q(s??null),s}catch(s){return console.error(s),null}},g=async()=>{if(!E.current){E.current=!0;try{for(;h.current&&(await l())?.status==="running";){if(!B()){await new Promise(n=>setTimeout(n,Z));continue}try{await w("tick")}catch(n){const v=typeof n=="object"&&n!==null&&"status"in n?Number(n.status):0;v&&(v===503||v>=500)?await new Promise(u=>setTimeout(u,je)):(console.error(n),await new Promise(u=>setTimeout(u,Z)));continue}finally{F()}await new Promise(n=>setTimeout(n,Z))}await l()}finally{E.current=!1}}};o.useEffect(()=>(h.current=!0,l().then(s=>{s?.status==="running"&&g()}),N.current=setInterval(l,5e3),()=>{h.current=!1,N.current&&clearInterval(N.current)}),[]);const J=async()=>{T(!0);try{await w("start",{only_fallback_author:j,fallback_author_name:A.trim()||te}),await l(),g()}catch(s){console.error(s),alert(`Не удалось запустить: ${s instanceof Error?s.message:String(s)}`)}finally{T(!1)}},U=async()=>{T(!0);try{await w("stop"),await l()}finally{T(!1)}},d=a?.status==="running",O=a?.status==="completed",b=a&&a.total>0?Math.min(100,a.processed/a.total*100):0;return e.jsxs("div",{className:"bg-card border border-border rounded-md p-6 mb-6 max-w-2xl",children:[e.jsxs("h2",{className:"font-serif text-xl font-bold mb-2 flex items-center gap-2",children:[e.jsx(he,{className:"h-5 w-5"}),"Восстановление гостевых авторов"]}),e.jsxs("p",{className:"text-sm text-muted-foreground mb-4",children:["Перебирает статьи, скачивает HTML с публичного сайта и подставляет реального автора из ",e.jsx("code",{children:'<meta name="author">'}),". Полезно после миграции из WordPress, где гостевые авторы (Molongui) были склеены в одного аккаунта-публикатора."]}),e.jsxs("div",{className:"space-y-3 mb-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(xe,{id:"only-fallback",checked:j,onCheckedChange:C,disabled:d}),e.jsx(Q,{htmlFor:"only-fallback",className:"text-sm cursor-pointer",children:"Только статьи с автором-«свалкой»"})]}),j&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(Q,{htmlFor:"fallback-name",className:"text-xs text-muted-foreground",children:"Имя автора-свалки"}),e.jsx(re,{id:"fallback-name",value:A,onChange:s=>H(s.target.value),disabled:d,spellCheck:!1})]})]}),a&&e.jsxs("div",{className:"mb-4 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground",children:[e.jsxs("span",{children:[d&&e.jsx(S,{className:"inline h-3 w-3 animate-spin mr-1"}),O&&e.jsx(P,{className:"inline h-3 w-3 text-green-600 mr-1"}),a.status==="failed"&&e.jsx(ne,{className:"inline h-3 w-3 text-destructive mr-1"}),"Статус: ",e.jsx("strong",{children:a.status})]}),e.jsxs("span",{children:[a.processed," / ",a.total]})]}),e.jsx(ae,{value:b}),e.jsxs("div",{className:"grid grid-cols-3 gap-2 text-xs text-muted-foreground pt-1",children:[e.jsxs("div",{children:["Обработано: ",e.jsx("strong",{className:"text-foreground",children:a.processed})]}),e.jsxs("div",{children:["Перепривязано: ",e.jsx("strong",{className:"text-foreground",children:a.updated_count})]}),e.jsxs("div",{children:["Новых авторов: ",e.jsx("strong",{className:"text-foreground",children:a.created_authors})]})]}),a.last_slug&&e.jsxs("div",{className:"text-xs text-muted-foreground truncate",children:["Последний slug: ",e.jsx("code",{className:"font-mono",children:a.last_slug})]}),a.error&&!a.error.startsWith("__config:")&&!a.error.startsWith("__state:")&&e.jsxs("div",{className:"text-xs text-destructive",children:["Ошибка: ",a.error]}),a.errors&&a.errors.length>0&&e.jsxs("details",{className:"text-xs",children:[e.jsxs("summary",{className:"cursor-pointer text-muted-foreground",children:["Сообщения (",a.errors.length,")"]}),e.jsx("div",{className:"max-h-40 overflow-auto mt-1 p-2 bg-muted/30 rounded",children:a.errors.slice(-50).map((s,n)=>e.jsx("p",{className:"font-mono text-[11px] text-muted-foreground break-all",children:s},n))})]})]}),e.jsx("div",{className:"flex gap-2",children:d?e.jsxs(I,{onClick:U,variant:"destructive",disabled:t,children:[t?e.jsx(S,{className:"h-4 w-4 animate-spin mr-1"}):e.jsx(le,{className:"h-4 w-4 mr-1"}),"Остановить"]}):e.jsxs(I,{onClick:J,disabled:t,children:[t?e.jsx(S,{className:"h-4 w-4 animate-spin mr-1"}):e.jsx(oe,{className:"h-4 w-4 mr-1"}),O||a?.status==="failed"?"Запустить заново":"Запустить"]})})]})}function Je(){const{isAdmin:a,loading:q}=ue();if(!q&&!a)return e.jsx(fe,{to:"/admin",replace:!0});
1const[t,T]=o.useState(null),[j,C]=o.useState(!0),[A,H]=o.useState(1),[N,E]=o.useState(!1),[h,w]=o.useState(null),[B,F]=o.useState(!1),[l,g]=o.useState(null),[J,U]=o.useState(!1),[d,O]=o.useState(null),b=o.useRef(null),s=async(r,c)=>{const{data:{session:x}}=await $.auth.getSession();if(!x?.access_token)throw new Error("Not authenticated");const i=await fetch(`/supabase/functions/v1/${r}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${x.access_token}`,apikey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Imhid3B3eHlwdmtuY3l2dnVlcWtmIiwicm9sZSI6ImFub24iLCJpYXQiOjE3ODM0ODA3ODAsImV4cCI6MjA5OTA1Njc4MH0.EobqTstpDfZAkM_3b3hkx_1ycMusd5BugnvCzcujxhE"},body:JSON.stringify(c)});if(!i.ok){const M=await i.text();throw new Error(`HTTP ${i.status}: ${M}`)}return i.json()},n=async()=>{try{const r=await s("import-wordpress-batch",{action:"status"});return T(r),r}catch{}finally{C(!1)}};o.useEffect(()=>(n(),()=>{b.current&&clearInterval(b.current)}),[]),o.useEffect(()=>{t?.status==="running"?b.current||(b.current=setInterval(n,5e3)):b.current&&(clearInterval(b.current),b.current=null)},[t?.status]);const v=async()=>{C(!0);try{await s("import-wordpress-batch",{action:"start",start_page:A}),await n()}catch(r){alert("Ошибка запуска: "+r.message),C(!1)}},u=async()=>{C(!0);try{await s("import-wordpress-batch",{action:"stop"}),await n()}catch(r){alert("Ошибка остановки: "+r.message),C(!1)}},D=async r=>{const c=r.target.files?.[0];if(c){E(!0),w(null);try{const i=(await c.text()).trim().split(`
2`),M=i[0]?.toLowerCase().includes("slug")?1:0,L=p=>{let f=p.trim().replace(/^"|"$/g,"");try{f=new URL(f).pathname}catch{}const _=f.replace(/^\/+|\/+$/g,"").split("/");return _[_.length-1]||f},y=[];for(let p=M;p<i.length;p++){const f=i[p].split(",");if(f.length<2)continue;const _=L(f[0]),V=parseInt(f[1].trim().replace(/^"|"$/g,""),10);_&&!isNaN(V)&&V>0&&y.push({slug:_,views:V})}const k=200;let m=0,R=0;for(let p=0;p<y.length;p+=k){const f=y.slice(p,p+k),_=await s("import-views",{entries:f});m+=_.updated||0,R+=_.not_found||0,w({updated:m,not_found:R})}w({updated:m,not_found:R})}catch(x){w({error:x.message})}finally{E(!1),r.target.value=""}}},ce=async()=>{F(!0),g(null);try{const{data:r}=await $.from("service_snippets").select("link_slug"),c=(r||[]).map(m=>m.link_slug);let x=$.from("articles").select("published_at").eq("status","published").order("published_at",{ascending:!1}).limit(1);for(const m of c)x=x.neq("slug",m);const{data:i}=await x.single();if(!i?.published_at){g({error:"Не найдены существующие статьи"});return}const M=new Date(i.published_at).toISOString(),L=await s("import-wordpress",{action:"count",per_page:100,after:M});if(!L.total||L.total===0){g({total:0,imported:0});return}let y=0;const k=[];for(let m=1;m<=L.totalPages;m++){const R=await s("import-wordpress",{action:"posts",page:m,per_page:100,after:M});y+=R.imported||0,R.errors?.length&&k.push(...R.errors),g({total:L.total,imported:y,errors:k.length>0?k:void 0})}if(g({total:L.total,imported:y,errors:k.length>0?k:void 0}),y>0)try{await fetch("/supabase/functions/v1/sitemap?action=refresh",{method:"GET"})}catch{}}catch(r){g({error:r.message})}finally{F(!1)}},ie=async()=>{if(confirm("Отправить все публичные URL сайта в IndexNow (Яндекс/Bing)? Это нужно делать только при первичной настройке.")){U(!0),O(null);try{const r=await s("indexnow",{action:"all"});O(r)}catch(r){O({error:r.message})}finally{U(!1)}}},z=t?.status==="running",de=t?.status==="completed",Y=t?.status==="stopped",X=t?.total_pages?Math.round(t.current_page/t.total_pages*100):0,me={categories:"Категории",tags:"Теги",authors:"Авторы",posts:"Статьи"};return e.jsxs("div",{children:[e.jsx("h1",{className:"font-serif text-2xl font-bold mb-6",children:"Импорт из WordPress"}),e.jsxs("div",{className:"bg-card border border-border rounded-md p-6 mb-6 max-w-2xl",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Фоновый серверный импорт контента из WordPress (hashtelegraph.com)."}),j&&!t?e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-sm mb-4",children:[e.jsx(S,{className:"h-4 w-4 animate-spin"}),"Загрузка статуса..."]}):e.jsxs(e.Fragment,{children:[z&&e.jsxs("div",{className:"mb-4 p-3 bg-primary/10 border border-primary/20 rounded-md",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium mb-2",children:[e.jsx(S,{className:"h-4 w-4 animate-spin text-primary"}),"Импорт выполняется — ",me[t?.current_step||""]||t?.current_step]}),t?.current_step==="posts"&&e.jsxs(e.Fragment,{children:[e.jsx(ae,{value:X,className:"h-2 mb-1"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Страница ",t.current_page,"/",t.total_pages," • Импортировано: ",t.total_imported," статей • ",X,"%"]})]}),t?.current_step==="tags"&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Страница тегов: ",t.current_page]})]}),de&&e.jsx("div",{className:"mb-4 p-3 bg-green-500/10 border border-green-500/20 rounded-md",children:e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium text-green-700",children:[e.jsx(P,{className:"h-4 w-4"}),"Импорт завершён! Импортировано ",t?.total_imported," статей"]})}),Y&&e.jsx("div",{className:"mb-4 p-3 bg-yellow-500/10 border border-yellow-500/20 rounded-md",children:e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium text-yellow-700",children:[e.jsx(ne,{className:"h-4 w-4"}),"Импорт остановлен на странице ",t?.current_page]})}),t?.errors&&t.errors.length>0&&e.jsxs("div",{className:"mb-4 p-3 bg-destructive/10 border border-destructive/20 rounded-md max-h-40 overflow-auto",children:[e.jsxs("p",{className:"text-xs font-medium text-destructive mb-1",children:["Ошибки (",t.errors.length,"):"]}),t.errors.map((r,c)=>e.jsx("p",{className:"text-xs text-destructive/80 font-mono",children:r},c))]}),!z&&e.jsx("div",{className:"flex items-end gap-3 mb-4",children:e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Начать со страницы"}),e.jsx(re,{type:"number",min:1,value:A,onChange:r=>H(Number(r.target.value)||1),className:"w-32"})]})}),e.jsxs("div",{className:"flex gap-3",children:[!z&&e.jsxs(I,{onClick:v,disabled:j,children:[e.jsx(oe,{className:"h-4 w-4 mr-1"}),Y?`Перезапустить (стр. ${A})`:"Запустить импорт"]}),z&&e.jsxs(I,{variant:"destructive",onClick:u,disabled:j,children:[e.jsx(le,{className:"h-4 w-4 mr-1"}),"Остановить"]}),e.jsxs(I,{variant:"outline",onClick:n,disabled:j,children:[e.jsx(ge,{className:"h-4 w-4 mr-1"}),"Обновить статус"]})]})]})]}),e.jsxs("div",{className:"bg-card border border-border rounded-md p-6 mb-6 max-w-2xl",children:[e.jsxs("h2",{className:"font-serif text-xl font-bold mb-2 flex items-center gap-2",children:[e.jsx(pe,{className:"h-5 w-5"}),"Медиафайлы"]}),e.jsxs("div",{className:"p-3 bg-green-500/10 border border-green-500/20 rounded-md",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium text-green-700",children:[e.jsx(P,{className:"h-4 w-4"}),"Медиа размещены на Cloudflare R2, ссылки в статьях переписаны"]}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:["Структура путей сохранена: ",e.jsx("code",{children:"/wp-content/uploads/..."}),". Новые загрузки из редактора идут напрямую на R2."]})]})]}),e.jsxs("div",{className:"bg-card border border-border rounded-md p-6 mb-6 max-w-2xl",children:[e.jsxs("h2",{className:"font-serif text-xl font-bold mb-2 flex items-center gap-2",children:[e.jsx(G,{className:"h-5 w-5"}),"Импорт просмотров"]}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Загрузите CSV-файл (slug,views) для обновления счётчиков просмотров статей."}),h&&!h.error&&e.jsx("div",{className:"mb-4 p-3 bg-green-500/10 border border-green-500/20 rounded-md",children:e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium text-green-700",children:[e.jsx(P,{className:"h-4 w-4"}),"Обновлено: ",h.updated," статей, не найдено: ",h.not_found]})}),h?.error&&e.jsx("div",{className:"mb-4 p-3 bg-destructive/10 border border-destructive/20 rounded-md",children:e.jsx("p",{className:"text-xs text-destructive",children:h.error})}),e.jsxs("label",{children:[e.jsx("input",{type:"file",accept:".csv",className:"hidden",onChange:D,disabled:N}),e.jsx(I,{asChild:!0,disabled:N,children:e.jsxs("span",{children:[N?e.jsx(S,{className:"h-4 w-4 animate-spin mr-1"}):e.jsx(G,{className:"h-4 w-4 mr-1"}),N?"Загрузка...":"Загрузить CSV"]})})]})]}),e.jsxs("div",{className:"bg-card border border-border rounded-md p-6 mb-6 max-w-2xl",children:[e.jsxs("h2",{className:"font-serif text-xl font-bold mb-2 flex items-center gap-2",children:[e.jsx(ee,{className:"h-5 w-5"}),"Синхронизация новых статей"]}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Загрузить статьи, опубликованные на основном сайте после последнего импорта."}),l&&!l.error&&e.jsx("div",{className:"mb-4 p-3 bg-green-500/10 border border-green-500/20 rounded-md",children:e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium text-green-700",children:[e.jsx(P,{className:"h-4 w-4"}),"Найдено: ",l.total,", импортировано: ",l.imported]})}),l?.error&&e.jsx("div",{className:"mb-4 p-3 bg-destructive/10 border border-destructive/20 rounded-md",children:e.jsx("p",{className:"text-xs text-destructive",children:l.error})}),l?.errors&&l.errors.length>0&&e.jsxs("div",{className:"mb-4 p-3 bg-destructive/10 border border-destructive/20 rounded-md max-h-40 overflow-auto",children:[e.jsx("p",{className:"text-xs font-medium text-destructive mb-1",children:"Ошибки:"}),l.errors.map((r,c)=>e.jsx("p",{className:"text-xs text-destructive/80 font-mono",children:r},c))]}),e.jsxs(I,{onClick:ce,disabled:B,children:[B?e.jsx(S,{className:"h-4 w-4 animate-spin mr-1"}):e.jsx(ee,{className:"h-4 w-4 mr-1"}),B?"Синхронизация...":"Синхронизировать"]})]}),e.jsxs("div",{className:"bg-card border border-border rounded-md p-6 mb-6 max-w-2xl",children:[e.jsxs("h2",{className:"font-serif text-xl font-bold mb-2 flex items-center gap-2",children:[e.jsx(se,{className:"h-5 w-5"}),"IndexNow — массовая отправка"]}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Отправить все публичные URL сайта (главная, статьи, категории, теги) в IndexNow для индексации в Яндексе и Bing. Нужно сделать один раз при первичной настройке. Новые статьи пингуются автоматически при публикации."}),d&&!d.error&&e.jsxs("div",{className:"mb-4 p-3 bg-green-500/10 border border-green-500/20 rounded-md",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium text-green-700 mb-2",children:[e.jsx(P,{className:"h-4 w-4"}),"Отправлено URL: ",d.submitted,", пачек: ",d.batches]}),d.details?.map((r,c)=>e.jsxs("div",{className:"text-xs text-muted-foreground font-mono",children:["Пачка ",c+1," (",r.size," URL): ",Object.entries(r.results).map(([x,i])=>`${new URL(x).hostname}=${i}
2`).join(", ")]},c))]}),d?.error&&e.jsx("div",{className:"mb-4 p-3 bg-destructive/10 border border-destructive/20 rounded-md",children:e.jsx("p",{className:"text-xs text-destructive",children:d.error})}),e.jsxs(I,{onClick:ie,disabled:J,children:[J?e.jsx(S,{className:"h-4 w-4 animate-spin mr-1"}):e.jsx(se,{className:"h-4 w-4 mr-1"}),J?"Отправка...":"Отправить все URL"]})]}),e.jsx(Ne,{})]})}export{Je as default};

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.