diff --git a/CHANGELOG.md b/CHANGELOG.md index 264c87cd..3cf16cb6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,11 @@ +## ZeroNet 0.5.1 (2016-11-18) +### Added +- Multi language interface +- New plugin: Translation helper for site html and js files +- Per-site favicon + +### Fixed +- Parallel optional file downloading ## ZeroNet 0.5.0 (2016-11-08) ### Added diff --git a/plugins/MergerSite/MergerSitePlugin.py b/plugins/MergerSite/MergerSitePlugin.py index 80bff92f..4440e718 100644 --- a/plugins/MergerSite/MergerSitePlugin.py +++ b/plugins/MergerSite/MergerSitePlugin.py @@ -2,6 +2,7 @@ import re import time from Plugin import PluginManager +from Translate import Translate from util import RateLimit from util import helper try: @@ -15,6 +16,8 @@ if "merger_db" not in locals().keys(): # To keep merger_sites between module re merged_to_merger = {} # {address: [site1, site2, ...]} cache site_manager = None # Site manager for merger sites +if "_" not in locals(): + _ = Translate("plugins/MergerSite/languages/") # Check if the site has permission to this merger site def checkMergerPath(address, inner_path): @@ -56,7 +59,7 @@ class UiWebsocketPlugin(object): else: self.cmd( "confirm", - ["Add %s new site?" % len(addresses), "Add"], + [_["Add %s new site?"] % len(addresses), "Add"], lambda (res): self.cbMergerSiteAdd(to, addresses) ) self.response(to, "ok") @@ -68,7 +71,7 @@ class UiWebsocketPlugin(object): added += 1 site_manager.need(address) if added: - self.cmd("notification", ["done", "Added %s new site" % added, 5000]) + self.cmd("notification", ["done", _["Added %s new site"] % added, 5000]) RateLimit.called(self.site.address + "-MergerSiteAdd") site_manager.updateMergerSites() @@ -84,7 +87,7 @@ class UiWebsocketPlugin(object): if merged_db.get(address) not in merger_types: return self.response(to, {"error": "Merged type (%s) not in %s" % (merged_db.get(address), merger_types)}) - self.cmd("notification", ["done", "Site deleted: %s" % address, 5000]) + self.cmd("notification", ["done", _["Site deleted: %s"] % address, 5000]) self.response(to, "ok") # Lists merged sites diff --git a/plugins/MergerSite/languages/hu.json b/plugins/MergerSite/languages/hu.json new file mode 100644 index 00000000..8e377aaa --- /dev/null +++ b/plugins/MergerSite/languages/hu.json @@ -0,0 +1,5 @@ +{ + "Add %s new site?": "Új oldal hozzáadása: %s?", + "Added %s new site": "Új oldal hozzáadva: %s", + "Site deleted: %s": "Oldal törölve: %s" +} diff --git a/plugins/OptionalManager/UiWebsocketPlugin.py b/plugins/OptionalManager/UiWebsocketPlugin.py index eecf225f..91f7f6f8 100644 --- a/plugins/OptionalManager/UiWebsocketPlugin.py +++ b/plugins/OptionalManager/UiWebsocketPlugin.py @@ -7,7 +7,10 @@ import gevent from Plugin import PluginManager from Config import config from util import helper +from Translate import Translate +if "_" not in locals(): + _ = Translate("plugins/OptionalManager/languages/") @PluginManager.registerTo("UiWebsocket") class UiWebsocketPlugin(object): @@ -99,13 +102,13 @@ class UiWebsocketPlugin(object): def actionOptionalFilePin(self, to, inner_path, address=None): back = self.setPin(inner_path, 1, address) if back == "ok": - self.cmd("notification", ["done", "Pinned %s files" % len(inner_path) if type(inner_path) is list else 1, 5000]) + self.cmd("notification", ["done", _["Pinned %s files"] % len(inner_path) if type(inner_path) is list else 1, 5000]) self.response(to, back) def actionOptionalFileUnpin(self, to, inner_path, address=None): back = self.setPin(inner_path, 0, address) if back == "ok": - self.cmd("notification", ["done", "Removed pin from %s files" % len(inner_path) if type(inner_path) is list else 1, 5000]) + self.cmd("notification", ["done", _["Removed pin from %s files"] % len(inner_path) if type(inner_path) is list else 1, 5000]) self.response(to, back) def actionOptionalFileDelete(self, to, inner_path, address=None): @@ -202,7 +205,7 @@ class UiWebsocketPlugin(object): self.cmd("notification", [ "done", - "You started to help distribute %s.
Directory: %s" % + _["You started to help distribute %s.
Directory: %s"] % (cgi.escape(title), cgi.escape(directory)), 10000 ]) @@ -247,8 +250,8 @@ class UiWebsocketPlugin(object): self.cmd( "confirm", [ - "Help distribute all new optional files on site %s" % cgi.escape(site_title), - "Yes, I want to help!" + _["Help distribute all new optional files on site %s"] % cgi.escape(site_title), + _["Yes, I want to help!"] ], lambda (res): self.cbOptionalHelpAll(to, site, True) ) diff --git a/plugins/OptionalManager/languages/hu.json b/plugins/OptionalManager/languages/hu.json new file mode 100644 index 00000000..7a23b86c --- /dev/null +++ b/plugins/OptionalManager/languages/hu.json @@ -0,0 +1,7 @@ +{ + "Pinned %s files": "%s fájl rögzítve", + "Removed pin from %s files": "%s fájl rögzítés eltávolítva", + "You started to help distribute %s.
Directory: %s": "Új segítség a terjesztésben: %s.
Könyvtár: %s", + "Help distribute all new optional files on site %s": "Segítség az összes új opcionális fájl terjesztésében az %s oldalon", + "Yes, I want to help!": "Igen, segíteni akarok!" +} diff --git a/plugins/PeerDb/PeerDbPlugin.py b/plugins/PeerDb/PeerDbPlugin.py index 87a8eb85..05de8fe0 100644 --- a/plugins/PeerDb/PeerDbPlugin.py +++ b/plugins/PeerDb/PeerDbPlugin.py @@ -63,6 +63,9 @@ class ContentDbPlugin(object): if spawn: # Save peers every hour (+random some secs to not update very site at same time) gevent.spawn_later(60 * 60 + random.randint(0, 60), self.savePeers, site, spawn=True) + if not site.peers: + site.log.debug("Peers not saved: No peers found") + return s = time.time() site_id = self.site_ids.get(site.address) cur = self.getCursor() diff --git a/plugins/Sidebar/SidebarPlugin.py b/plugins/Sidebar/SidebarPlugin.py index 9b785a8e..c9e71f13 100644 --- a/plugins/Sidebar/SidebarPlugin.py +++ b/plugins/Sidebar/SidebarPlugin.py @@ -24,7 +24,7 @@ sys.path.append(plugin_dir) # To able to load geoip lib loc_cache = {} if "_" not in locals(): - _ = Translate("plugins/Sidebar/languages/") + _ = Translate(plugin_dir + "/languages/") @PluginManager.registerTo("UiRequest") diff --git a/plugins/Sidebar/languages/fr.json b/plugins/Sidebar/languages/fr.json index bc52c57e..5c4b3ac7 100644 --- a/plugins/Sidebar/languages/fr.json +++ b/plugins/Sidebar/languages/fr.json @@ -37,6 +37,7 @@ "Identity address": "Adresse d'identité", "Change": "Modifier", + "Site control": "Opérations", "Update": "Mettre à jour", "Pause": "Suspendre", "Resume": "Reprendre", diff --git a/plugins/Sidebar/languages/ru.json b/plugins/Sidebar/languages/ru.json index 156b0a8a..f2eeca04 100644 --- a/plugins/Sidebar/languages/ru.json +++ b/plugins/Sidebar/languages/ru.json @@ -37,6 +37,7 @@ "Identity address": "Уникальный адрес", "Change": "Изменить", + "Site control": "Управление сайтом", "Update": "Обновить", "Pause": "Пауза", "Resume": "Продолжить", diff --git a/plugins/Sidebar/languages/tr.json b/plugins/Sidebar/languages/tr.json new file mode 100644 index 00000000..88fcd6e0 --- /dev/null +++ b/plugins/Sidebar/languages/tr.json @@ -0,0 +1,82 @@ +{ + "Peers": "Eşler", + "Connected": "Bağlı", + "Connectable": "Erişilebilir", + "Connectable peers": "Bağlanılabilir eşler", + + "Data transfer": "Veri aktarımı", + "Received": "Alınan", + "Received bytes": "Bayt alındı", + "Sent": "Gönderilen", + "Sent bytes": "Bayt gönderildi", + + "Files": "Dosyalar", + "Total": "Toplam", + "Image": "Resim", + "Other": "Diğer", + "User data": "Kullanıcı verisi", + + "Size limit": "Boyut sınırı", + "limit used": "kullanılan", + "free space": "boş", + "Set": "Ayarla", + + "Optional files": "İsteğe bağlı dosyalar", + "Downloaded": "İndirilen", + "Download and help distribute all files": "Tüm dosyaları indir ve yayılmalarına yardım et", + "Total size": "Toplam boyut", + "Downloaded files": "İndirilen dosyalar", + + "Database": "Veritabanı", + "search feeds": "kaynak ara", + "{feeds} query": "{feeds} sorgu", + "Reload": "Yenile", + "Rebuild": "Yapılandır", + "No database found": "Veritabanı yok", + + "Identity address": "Kimlik adresi", + "Change": "Değiştir", + + "Site control": "Site kontrolü", + "Update": "Güncelle", + "Pause": "Duraklat", + "Resume": "Sürdür", + "Delete": "Sil", + "Are you sure?": "Emin misin?", + + "Site address": "Site adresi", + "Donate": "Bağış yap", + + "Missing files": "Eksik dosyalar", + "{} try": "{} deneme", + "{} tries": "{} deneme", + "+ {num_bad_files} more": "+ {num_bad_files} tane daha", + + "This is my site": "Bu benim sitem", + "Site title": "Site başlığı", + "Site description": "Site açıklaması", + "Save site settings": "Site ayarlarını kaydet", + + "Content publishing": "İçerik yayımlanıyor", + "Choose": "Seç", + "Sign": "İmzala", + "Publish": "Yayımla", + + "This function is disabled on this proxy": "Bu özellik bu vekilde kullanılamaz", + "GeoLite2 City database download error: {}!
Please download manually and unpack to data dir:
{}": "GeoLite2 Şehir veritabanı indirme hatası: {}!
Lütfen kendiniz indirip aşağıdaki konuma açınınız:
{}", + "Downloading GeoLite2 City database (one time only, ~20MB)...": "GeoLite2 Şehir veritabanı indiriliyor (sadece bir kere, ~20MB)...", + "GeoLite2 City database downloaded!": "GeoLite2 Şehir veritabanı indirildi!", + + "Are you sure?": "Emin misiniz?", + "Site storage limit modified!": "Site saklama sınırı değiştirildi!", + "Database schema reloaded!": "Veritabanı şeması yeniden yüklendi!", + "Database rebuilding....": "Veritabanı yeniden inşa ediliyor...", + "Database rebuilt!": "Veritabanı yeniden inşa edildi!", + "Site updated!": "Site güncellendi!", + "Delete this site": "Bu siteyi sil", + "File write error: ": "Dosya yazma hatası: ", + "Site settings saved!": "Site ayarları kaydedildi!", + "Enter your private key:": "Özel anahtarınızı giriniz:", + " Signed!": " İmzala!", + "WebGL not supported": "WebGL desteklenmiyor" +} diff --git a/plugins/Trayicon/TrayiconPlugin.py b/plugins/Trayicon/TrayiconPlugin.py index c3ca6e20..a9254447 100644 --- a/plugins/Trayicon/TrayiconPlugin.py +++ b/plugins/Trayicon/TrayiconPlugin.py @@ -5,9 +5,12 @@ import atexit from Plugin import PluginManager from Config import config +from Translate import Translate allow_reload = False # No source reload supported in this plugin +if "_" not in locals(): + _ = Translate("plugins/Trayicon/languages/") @PluginManager.registerTo("Actions") class ActionsPlugin(object): @@ -46,14 +49,14 @@ class ActionsPlugin(object): (self.titleConsole, self.toggleConsole), (self.titleAutorun, self.toggleAutorun), "--", - ("ZeroNet Twitter", lambda: self.opensite("https://twitter.com/HelloZeroNet")), - ("ZeroNet Reddit", lambda: self.opensite("http://www.reddit.com/r/zeronet/")), - ("ZeroNet Github", lambda: self.opensite("https://github.com/HelloZeroNet/ZeroNet")), - ("Report bug/request feature", lambda: self.opensite("https://github.com/HelloZeroNet/ZeroNet/issues")), + (_["ZeroNet Twitter"], lambda: self.opensite("https://twitter.com/HelloZeroNet")), + (_["ZeroNet Reddit"], lambda: self.opensite("http://www.reddit.com/r/zeronet/")), + (_["ZeroNet Github"], lambda: self.opensite("https://github.com/HelloZeroNet/ZeroNet")), + (_["Report bug/request feature"], lambda: self.opensite("https://github.com/HelloZeroNet/ZeroNet/issues")), "--", - ("!Open ZeroNet", lambda: self.opensite("http://%s:%s/%s" % (ui_ip, config.ui_port, config.homepage) )), + (_["!Open ZeroNet"], lambda: self.opensite("http://%s:%s/%s" % (ui_ip, config.ui_port, config.homepage) )), "--", - ("Quit", self.quit), + (_["Quit"], self.quit), ) @@ -74,29 +77,30 @@ class ActionsPlugin(object): webbrowser.open(url, new=0) def titleIp(self): - title = "!IP: %s" % config.ip_external + title = "!IP: %s " % config.ip_external if self.main.file_server.port_opened: - title += " (active)" + title += _["(active)"] else: - title += " (passive)" + title += _["(passive)"] return title def titleConnections(self): - title = "Connections: %s" % len(self.main.file_server.connections) + title = _["Connections: %s"] % len(self.main.file_server.connections) return title def titleTransfer(self): - title = "Received: %.2f MB | Sent: %.2f MB" % ( + title = _["Received: %.2f MB | Sent: %.2f MB"] % ( float(self.main.file_server.bytes_recv) / 1024 / 1024, float(self.main.file_server.bytes_sent) / 1024 / 1024 ) return title def titleConsole(self): + translate = _["Show console window"] if self.console: - return "+Show console window" + return "+" + translate else: - return "Show console window" + return translate def toggleConsole(self): if self.console: @@ -126,10 +130,11 @@ class ActionsPlugin(object): return os.path.isfile(path) and open(path).read() == self.formatAutorun() def titleAutorun(self): + translate = _["Start ZeroNet when Windows starts"] if self.isAutorunEnabled(): - return "+Start ZeroNet when Windows starts" + return "+" + translate else: - return "Start ZeroNet when Windows starts" + return translate def toggleAutorun(self): if self.isAutorunEnabled(): diff --git a/plugins/Trayicon/languages/hu.json b/plugins/Trayicon/languages/hu.json new file mode 100644 index 00000000..56fef23a --- /dev/null +++ b/plugins/Trayicon/languages/hu.json @@ -0,0 +1,14 @@ +{ + "ZeroNet Twitter": "ZeroNet Twitter", + "ZeroNet Reddit": "ZeroNet Reddit", + "ZeroNet Github": "ZeroNet Github", + "Report bug/request feature": "Hiba bejelentés/ötletek", + "!Open ZeroNet": "!ZeroNet megnyitása", + "Quit": "Kilépés", + "(active)": "(aktív)", + "(passive)": "(passive)", + "Connections: %s": "Kapcsolatok: %s", + "Received: %.2f MB | Sent: %.2f MB": "Fogadott: %.2f MB | Küldött: %.2f MB", + "Show console window": "Parancssor mutatása", + "Start ZeroNet when Windows starts": "ZeroNet indítása a Windows-al együtt" +} diff --git a/plugins/Trayicon/languages/zh.json b/plugins/Trayicon/languages/zh.json new file mode 100644 index 00000000..270f2e88 --- /dev/null +++ b/plugins/Trayicon/languages/zh.json @@ -0,0 +1,14 @@ +{ + "ZeroNet Twitter": "ZeroNet Twitter", + "ZeroNet Reddit": "ZeroNet Reddit", + "ZeroNet Github": "ZeroNet Github", + "Report bug/request feature": "反馈问题/请求功能", + "!Open ZeroNet": "!打开 ZeroNet", + "Quit": "退出", + "(active)": "(激活)", + "(passive)": "(passive)", + "Connections: %s": "连接数: %s", + "Received: %.2f MB | Sent: %.2f MB": "已收到: %.2f MB | 已发送: %.2f MB", + "Show console window": "显示控制台窗口", + "Start ZeroNet when Windows starts": "在 Windows 启动时运行 ZeroNet" +} diff --git a/src/Config.py b/src/Config.py index d6718c31..1e7e5a5b 100644 --- a/src/Config.py +++ b/src/Config.py @@ -9,7 +9,7 @@ class Config(object): def __init__(self, argv): self.version = "0.5.1" - self.rev = 1756 + self.rev = 1766 self.argv = argv self.action = None self.config_file = "zeronet.conf" @@ -146,6 +146,8 @@ class Config(object): nargs='?', const="default_browser", metavar='browser_name') self.parser.add_argument('--homepage', help='Web interface Homepage', default='1HeLLo4uzjaLetFx6NH3PMwFP3qbRbTf3D', metavar='address') + self.parser.add_argument('--updatesite', help='Source code update site', default='1UPDatEDxnvHDo7TXvq6AEBARfNkyfxsp', + metavar='address') self.parser.add_argument('--size_limit', help='Default site size limit in MB', default=10, type=int, metavar='size') self.parser.add_argument('--connected_limit', help='Max connected peer per site', default=10, type=int, metavar='connected_limit') diff --git a/src/Content/ContentManager.py b/src/Content/ContentManager.py index adbba799..13142c13 100644 --- a/src/Content/ContentManager.py +++ b/src/Content/ContentManager.py @@ -279,6 +279,8 @@ class ContentManager(object): return self.contents.db.listModified(self.site, since) def listContents(self, inner_path="content.json", user_files=False): + if inner_path not in self.contents: + return [] back = [inner_path] content_inner_dir = helper.getDirname(inner_path) for relative_path in self.contents[inner_path].get("includes", {}).keys(): diff --git a/src/Site/SiteManager.py b/src/Site/SiteManager.py index ee22aa1b..6f35d13f 100644 --- a/src/Site/SiteManager.py +++ b/src/Site/SiteManager.py @@ -49,10 +49,16 @@ class SiteManager(object): self.log.debug("Removed site: %s" % address) # Remove orpan sites from contentdb - for row in ContentDb.getContentDb().execute("SELECT * FROM site"): - if row["address"] not in self.sites: - self.log.info("Deleting orphan site from content.db: %s" % row["address"]) - ContentDb.getContentDb().execute("DELETE FROM site WHERE ?", {"address": row["address"]}) + content_db = ContentDb.getContentDb() + for row in content_db.execute("SELECT * FROM site"): + address = row["address"] + if address not in self.sites: + self.log.info("Deleting orphan site from content.db: %s" % address) + content_db.execute("DELETE FROM site WHERE ?", {"address": address}) + if address in content_db.site_ids: + del content_db.site_ids[address] + if address in content_db.sites: + del content_db.sites[address] if added: self.log.debug("SiteManager added %s sites" % added) diff --git a/src/Translate/languages/tr.json b/src/Translate/languages/tr.json new file mode 100644 index 00000000..0bdabd89 --- /dev/null +++ b/src/Translate/languages/tr.json @@ -0,0 +1,51 @@ +{ + "Congratulation, your port {0} is opened.
You are full member of ZeroNet network!": "Tebrikler, portunuz ({0}) açık.
Artık ZeroNet ağına katıldınız!", + "Tor mode active, every connection using Onion route.": "Tor aktif, tüm bağlantılar Onion yönlendircisini kullanıyor.", + "Successfully started Tor onion hidden services.": "Gizli Tor hizmetleri başlatıldı.", + "Unable to start hidden services, please check your config.": "Gizli hizmetler başlatılamadı, lütfen ayarlarınızı kontrol ediniz.", + "For faster connections open {0} port on your router.": "Daha hızlı bağlantı için {0} nolu portu bilgisayarınıza yönlendirin.", + "Your connection is restricted. Please, open {0} port on your router": "Sınırlı bağlantı. Lütfen, {0} nolu portu bilgisayarınıza yönlendirin", + "or configure Tor to become full member of ZeroNet network.": "ya da ZeroNet ağına tam olarak katılabilmek için Tor'u kullanın.", + + "Select account you want to use in this site:": "Bu sitede kullanmak için bir hesap seçiniz:", + "currently selected": "kullanılan", + "Unique to site": "Bu site için benzersiz", + + "Content signing failed": "İçerik imzalama başarısız oldu", + "Content publish queued for {0:.0f} seconds.": "İçerik yayımlanmak üzere {0:.0f} saniyedir kuyrukta.", + "Content published to {0} peers.": "İçerik {0} eşe dağıtıldı.", + "No peers found, but your content is ready to access.": "Eş bulunamadı, ama içeriğiniz erişime hazır.", + "Your network connection is restricted. Please, open {0} port": "Sınırlı bağlantı. Lütfen, {0} nolu portu bilgisayarınıza yönlendirin", + "on your router to make your site accessible for everyone.": "böylece sitenizi herkes için erişilebilir yapabilirsiniz", + "Content publish failed.": "İçerik yayımlama başarısız oldu.", + "This file still in sync, if you write it now, then the previous content may be lost.": "Bu dosya hala güncelleniyor, eğer şimdi kaydederseniz, önceki içerik kaybolabilir.", + "Write content anyway": "Yine de kaydet", + "New certificate added:": "Yeni sertifika eklendi:", + "You current certificate:": "Kullanılan sertifikanız:", + "Change it to {auth_type}/{auth_user_name}@{domain}": "{auth_type}/{auth_user_name}@{domain} olarak değiştir.", + "Certificate changed to: {auth_type}/{auth_user_name}@{domain}.": "{auth_type}/{auth_user_name}@{domain} olarak değiştirildi", + "Site cloned": "Site klonlandı", + + "You have successfully changed the web interface's language!": "WEB ara yüzü için dil başarıyla değiştirildi!", + "Due to the browser's caching, the full transformation could take some minute.": "Tam dönüşümün sağlanması, tarayıcı önbelleklemesi yüzünden zaman alabilir.", + + "Connection with UiServer Websocket was lost. Reconnecting...": "UiServer Websocket ile bağlantı kesildi. Yeniden bağlanılıyor...", + "Connection with UiServer Websocket recovered.": "UiServer Websocket ile bağlantı yeniden kuruldu.", + "UiServer Websocket error, please reload the page.": "UiServer Websocket hatası, lütfen sayfayı yenileyin.", + "   Connecting...": "   Bağlanıyor...", + "Site size: ": "Site boyutu: ", + "MB is larger than default allowed ": "MB izin verilenden fazla ", + "Open site and set size limit to \" + site_info.next_size_limit + \"MB": "Siteyi açın ve boyut sınırını \" + site_info.next_size_limit + \"MB'ye yükseltin", + " files needs to be downloaded": " indirilmesi gereken dosyalar", + " downloaded": " indirildi", + " download failed": " indirme başarısız", + "Peers found: ": "Bulunan eşler: ", + "No peers found": "Eş bulunamadı", + "Running out of size limit (": "Boyut sınırlamasını aştı (", + "Set limit to \" + site_info.next_size_limit + \"MB": "Sınırlamayı \" + site_info.next_size_limit + \"MB'ye yükselt", + "Site size limit changed to {0}MB": "Site boyut sınırlaması {0}MB olarak ayarlandı", + " New version of this page has just released.
Reload to see the modified content.": " Bu sayfanın yeni versiyonu yayımlandı.
Değişen içeriği görmek için yeniden yükleyiniz.", + "This site requests permission:": "Bu site bir izin istiyor:", + "Grant": "İzin ver" + +} diff --git a/src/Ui/UiWebsocket.py b/src/Ui/UiWebsocket.py index 43dd552c..ff147a81 100644 --- a/src/Ui/UiWebsocket.py +++ b/src/Ui/UiWebsocket.py @@ -703,6 +703,7 @@ class UiWebsocket(object): sys.modules["main"].update_after_shutdown = True if sys.modules["main"].file_server.tor_manager.tor_process: sys.modules["main"].file_server.tor_manager.stopTor() + SiteManager.site_manager.save() sys.modules["main"].file_server.stop() sys.modules["main"].ui_server.stop() diff --git a/update.py b/update.py index fb7258e6..1ca15a1a 100644 --- a/update.py +++ b/update.py @@ -5,13 +5,14 @@ import ssl import httplib import socket import re +import json import cStringIO as StringIO from gevent import monkey monkey.patch_all() -def update(): +def download(): from src.util import helper urls = [ @@ -46,6 +47,27 @@ def update(): print "Downloaded." + return zipdata + + +def update(): + from Config import config + updatesite_path = config.data_dir + "/" + config.updatesite + sites_json = json.load(open(config.data_dir + "/sites.json")) + updatesite_bad_files = sites_json.get(config.updatesite, {}).get("cache", {}).get("bad_files", {}) + print "Update site path: %s, bad_files: %s" % (updatesite_path, len(updatesite_bad_files)) + if os.path.isfile(updatesite_path + "/content.json") and len(updatesite_bad_files) == 0 and sites_json.get(config.updatesite, {}).get("serving"): + # Update site exists and no broken file + print "Updating using site %s" % config.updatesite + zipdata = False + inner_paths = json.load(open(updatesite_path + "/content.json"))["files"].keys() + # Keep file only in ZeroNet directory + inner_paths = [inner_path for inner_path in inner_paths if inner_path.startswith("ZeroNet/")] + else: + # Fallback to download + zipdata = download() + inner_paths = zipdata.namelist() + # Checking plugins plugins_enabled = [] plugins_disabled = [] @@ -58,12 +80,12 @@ def update(): print "Plugins enabled:", plugins_enabled, "disabled:", plugins_disabled print "Extracting...", - for inner_path in zipdata.namelist(): + for inner_path in inner_paths: if ".." in inner_path: continue inner_path = inner_path.replace("\\", "/") # Make sure we have unix path print ".", - dest_path = re.sub("^[^/]*-master.*?/", "", inner_path) # Skip root zeronet-master-... like directories + dest_path = re.sub("^([^/]*-master.*?|ZeroNet)/", "", inner_path) # Skip root zeronet-master-... like directories dest_path = dest_path.lstrip("/") if not dest_path: continue @@ -84,7 +106,11 @@ def update(): os.makedirs(dest_dir) if dest_dir != dest_path.strip("/"): - data = zipdata.read(inner_path) + if zipdata: + data = zipdata.read(inner_path) + else: + data = open(updatesite_path + "/" + inner_path, "rb").read() + try: open(dest_path, 'wb').write(data) except Exception, err: diff --git a/zeronet.py b/zeronet.py index f8209672..f56161ee 100755 --- a/zeronet.py +++ b/zeronet.py @@ -10,8 +10,10 @@ def main(): main = None try: - sys.path.insert(0, os.path.join(os.path.dirname(__file__), "src/lib")) # External liblary directory - sys.path.insert(0, os.path.join(os.path.dirname(__file__), "src")) # Imports relative to src + app_dir = os.path.dirname(os.path.abspath(__file__)) + os.chdir(app_dir) # Change working dir to zeronet.py dir + sys.path.insert(0, os.path.join(app_dir, "src/lib")) # External liblary directory + sys.path.insert(0, os.path.join(app_dir, "src")) # Imports relative to src import main main.start() if main.update_after_shutdown: # Updater @@ -29,12 +31,12 @@ def main(): except Exception, err: print "Error closing pyelliptic lib", err - # Update - update.update() - # Close lock file sys.modules["main"].lock.close() + # Update + update.update() + # Close log files logger = sys.modules["main"].logging.getLogger() @@ -63,4 +65,4 @@ def main(): print "Bye." if __name__ == '__main__': - main() + main() \ No newline at end of file