Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import system
- import os
- import hashes
- import strutils
- import httpclient
- type
- SynchronizedFileInfo = object of RootObj
- url: string
- localPath: string
- localHash: Hash
- Config = ref object of RootObj
- infos: seq[SynchronizedFileInfo]
- proc loadConfig(): Config =
- let configFile = open("urlsync.cfg", mode=FileMode.fmReadWriteExisting)
- defer: close configFile
- var infos = newSeq[SynchronizedFileInfo]()
- var hashBytes: array[sizeof(Hash), uint8]
- while true:
- if configFile.readBytes(hashBytes, 0, sizeof(Hash)) < sizeof(Hash): break
- let hash = cast[ptr Hash](addr hashBytes)[]
- let sl = configFile.readLine().split("|", maxsplit=1)
- #if sl.len != 2: error
- var sfi = SynchronizedFileInfo(url:sl[0], localPath:sl[1], localHash:hash)
- infos.add(sfi)
- return Config(infos: infos)
- proc computeHash(file: File): Hash = file.readAll().hash()
- proc computeFileHash(filePath: string): Hash =
- let file = open(filePath, mode=FileMode.fmRead)
- defer: close file
- return computeHash(file)
- var config = loadConfig()
- echo repr(config)
- while true:
- sleep 1000*10 # 10 s
- for sfi in config.infos:
- var client = newHttpClient()
- defer: close client
- let downloadPath = sfi.localPath & ".new"
- if not os.existsFile(sfi.localPath):
- client.downloadFile(sfi.url, sfi.localPath)
- continue
- client.downloadFile(sfi.url, downloadPath)
- if computeFileHash(downloadPath) != computeFileHash(sfi.localPath):
- try:
- echo "updating " & sfi.localPath
- os.removeFile(sfi.localPath)
- os.moveFile(downloadPath, sfi.localPath)
- except OSError:
- echo getCurrentExceptionMsg()
- else:
- os.removeFile(downloadPath)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement