Advertisement
Guest User

Untitled

a guest
Sep 30th, 2017
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Nim 1.74 KB | None | 0 0
  1. import system
  2. import os
  3. import hashes
  4. import strutils
  5. import httpclient
  6.  
  7. type
  8.   SynchronizedFileInfo = object of RootObj
  9.     url: string
  10.     localPath: string
  11.     localHash: Hash
  12.   Config = ref object of RootObj
  13.     infos: seq[SynchronizedFileInfo]
  14.  
  15. proc loadConfig(): Config =
  16.   let configFile = open("urlsync.cfg", mode=FileMode.fmReadWriteExisting)
  17.   defer: close configFile
  18.   var infos = newSeq[SynchronizedFileInfo]()
  19.   var hashBytes: array[sizeof(Hash), uint8]
  20.   while true:
  21.     if configFile.readBytes(hashBytes, 0, sizeof(Hash)) < sizeof(Hash): break
  22.     let hash = cast[ptr Hash](addr hashBytes)[]
  23.     let sl = configFile.readLine().split("|", maxsplit=1)
  24.     #if sl.len != 2: error
  25.     var sfi = SynchronizedFileInfo(url:sl[0], localPath:sl[1], localHash:hash)
  26.     infos.add(sfi)        
  27.   return Config(infos: infos)
  28.  
  29. proc computeHash(file: File): Hash = file.readAll().hash()
  30.  
  31. proc computeFileHash(filePath: string): Hash =
  32.   let file = open(filePath, mode=FileMode.fmRead)
  33.   defer: close file
  34.   return computeHash(file)
  35.  
  36.  
  37. var config = loadConfig()
  38. echo repr(config)
  39.  
  40. while true:
  41.   sleep 1000*10 # 10 s
  42.  
  43.   for sfi in config.infos:
  44.     var client = newHttpClient()
  45.     defer: close client    
  46.     let downloadPath = sfi.localPath & ".new"
  47.     if not os.existsFile(sfi.localPath):
  48.       client.downloadFile(sfi.url, sfi.localPath)
  49.       continue
  50.     client.downloadFile(sfi.url, downloadPath)
  51.     if computeFileHash(downloadPath) != computeFileHash(sfi.localPath):
  52.       try:
  53.         echo "updating " & sfi.localPath
  54.         os.removeFile(sfi.localPath)
  55.         os.moveFile(downloadPath, sfi.localPath)
  56.       except OSError:
  57.         echo getCurrentExceptionMsg()
  58.     else:
  59.       os.removeFile(downloadPath)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement