#!/usr/bin/env python 
from bs4 import BeautifulSoup as bs
import requests as rq
from datetime import datetime
import shutil
import os

def downloadImage(link='', fout=''):
    r = rq.get(link)
    if r.status_code == 200:
        file_size = int(r.headers.get('Content-Length', 0))
        i=0
        with open(fout, 'wb') as f:
            shutil.copyfileobj(r.raw, f) 
            #for chunk in r.iter_content(1024):
            #    f.write(chunk)
            #    if (file_size > 0):
            #        i += 1
                #print("Downloading ...:", round(i*1024./float(file_size) * 100.,1),"% of", file_size,"Kb",)
        f.close()
        return True
    else:
        return False

url = "http://planet.iitp.ru/index.php?page_type=oper_prod&page=product&prod=97"
soup = bs(rq.get(url).content, 'html.parser')
divs = soup.find_all('div', attrs='descript')
links = []
times = []
for img in divs:
    a = img.find(href=True)
    links.append(a['href'])
    times.append(a.text)
times = [datetime.strptime(t, '%Y-%m-%d %H:%M:%S') for t in times]
print('Start Downloading: %s'%(datetime.now().strftime("%Y-%m-%dT%H:%M:%S")))
for i in range(len(links)):
    fout=times[i].strftime('/var/www/sat/planet_%H.jpg') 
    if downloadImage(link=links[i], fout=fout):
        print('Image (%s) was Downloaded successfully!'%(links[i]))
        os.system('touch -t %s %s'%(times[i].strftime("%Y%m%d%H%M.%S"), fout))
    else:
        print('Something went wrong while downloading the Image (%)'%(links[i]))
print('Stop Downloading: %s'%(datetime.now().strftime("%Y-%m-%dT%H:%M:%S")))
os.system('ls -trl /var/www/sat/planet*.jpg > flist.txt')


