Completed
Push — master ( 157144...4bac54 )
by Sepand
50s
created

sample_site_download()   A

Complexity

Conditions 4

Size

Total Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 2 Features 0
Metric Value
cc 4
c 2
b 2
f 0
dl 0
loc 15
rs 9.2
1
import os
2
import shutil  # Library For Work With File In High Level Like Copy
3
import datetime  # For Adding System Time To Homepage
4
import webbrowser
5
from params import *
6
import socket
7
import requests
8
import re
9
import time
10
import sys
11
import urllib.request
12
meta_input=""
13
14
def download_lorem():
15
    if internet():
16
        urllib.request.urlretrieve("http://www.qpage.ir/sample/Latin-Lipsum.txt","Latin-Lipsum.txt")
17
    else:
18
        print("Error In Download Lorem")
19
def read_lorem(char=100):
20
    try:
21
        if "Latin-Lipsum.txt"  not in os.listdir():
22
            download_lorem()
23
        lorem_file=open("Latin-Lipsum.txt","r")
24
        lorem_text=lorem_file.read()
25
        lorem_file.close()
26
        return " ".join(lorem_text.split(" ")[:char])
27
    except:
28
        return None
29
def sample_site_download():
30
    try:
31
        if internet():
32
            for i in range(len(sample_dict_addr.keys())):
33
                print("Downloading "+ sample_dict_message[i]+" . . . ["+str(i+1)+"/4]")
34
                print_line(70)
35
                urllib.request.urlretrieve(list(sample_dict_addr.values())[i],os.path.join(image_dir,list(sample_dict_addr.keys())[i]))
36
            print("Done!")
37
            print_line(70)
38
        else:
39
            print("Error In Internet Connection!")
40
            print_line(70)
41
    except:
42
        print("Error in downloading sample files check your internet conection")
43
        print_line(70)
44
def logger(status=False):
45
    file=open("build_log.txt","a")
46
    if status==False:
47
        file.write("Faild  "+str(datetime.datetime.now())+"\n")
48
    else:
49
        file.write("Sucess "+str(datetime.datetime.now())+"\n")
50
    file.close()
51
52
53
def print_line(number,char="-"):
54
    line=""
55
    for i in range(number):
56
        line=line+char
57
    print(line)
58
59
def name_standard(name):
60
    reponse_name=name[0].upper()+name[1:].lower()
61
    return reponse_name
62
def address_print():
63
    print_line(70,"*")
64
    print("Where--> "+work_dir)
65
    print_line(70, "*")
66
def create_folder():  # This Function Create Empty Folder At Begin
67
    folder_flag = 0
68
    list_of_folders = os.listdir(work_dir)
69
    for i in ["doc","image","output","font"]:
70
        if i not in list_of_folders:
71
            os.mkdir(i)
72
            folder_flag += 1
73
            if i=="doc":
74
                file = open(os.path.join(doc_dir, "index.txt"), "w")
75
                if read_lorem()==None:
76
                    file.write("This is For First Page . . .")
77
                else:
78
                    file.write(read_lorem())
79
                file.close()
80
    return bool(folder_flag)
81
82
83
def page_name_update():  # This Function Update Page Names
84
    for i in os.listdir(doc_dir):
85
        if i.find(".txt") != -1 and i[:-4].upper() != "INDEX":
86
            actual_name.append(i[:-4])
87
            page_name.append(i[:-4])
88
89
90
def menu_maker():  # Top Menu Maker In each html page
91
    result = "<center>"
92
    for i in range(len(page_name)):
93
        if page_name[i] == "Home":
94
            targets_blank = ""
95
        else:
96
            targets_blank = 'target="blank"'
97
        result = result + '\t<a href="' + actual_name[i] + '.html"' + targets_blank + '>' + name_standard(page_name[
98
            i]) + "</a>\n"  # Hyper Link To Each Page In HTML File
99
        result += "&nbsp\n"
100
    result += "</center>"
101
    result = result + "\t\t" + break_line  # Add Break line to End Of The Menu
102
    return result  # Return All Of The Menu
103
104
105
def menu_writer():  # Write menu_maker output in html file
106
    message = menu_maker()
107
    for i in range(len(page_name)):
108
        file = open(os.path.join(out_dir, actual_name[i] + ".html"), "a")
109
        file.write(message)
110
        file.close()
111
112
113
def print_meta():
114
    global meta_input
115
    meta_input = input("Please Enter Your Name : ")
116
    static_meta = '<meta name="description" content="Welcome to homepage of ' + meta_input + '"/>\n'
117
    static_meta=static_meta+'<meta property="og:title" content="'+meta_input+'"/>\n'
118
    static_meta=static_meta+'<meta property="og:site_name" content="'+meta_input+'"/>\n'
119
    static_meta=static_meta+'<meta property="og:image" content="favicon.ico" />\n'
120
    if len(meta_input) < 4:
121
        warnings.append("[Warning] Your input for name is too short!!")
122
    return static_meta
123
124
125
def html_init(name):  # Create Initial Form Of each Html Page Like Title And HTML  And Body Tag
126
    html_name = os.path.join(out_dir, name + ".html")
127
    file = open(html_name, "w")
128
    file.write("<html>\n")
129
    file.write("\t<head>\n")
130
    if name == "index":
131
        file.write("\t\t<title>Welcome To My Homepage</title>\n")
132
    else:
133
        file.write("\t\t<title>" + name_standard(name) + "</title>\n")
134
    file.write('<link rel="stylesheet" href="styles.css" type="text/css"/>\n')
135
    css_link = 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css'
136
    file.write('<link rel="stylesheet" href= ' + css_link + ' type="text/style"/>\n')
137
138
    if name == 'index':  # Add meta only for index page
139
        file.write(print_meta())
140
141
    file.write("\t</head>\n")
142
    file.write('\t<body class="body_tag">\n')
143
    file.close()
144
145
146
def html_end(name):  # Create End Of The Html file
147
    html_name = os.path.join(out_dir, name + ".html")
148
    file = open(html_name, "a")
149
    file.write("\t</body>\n")
150
    file.write("</html>")
151
    file.close()
152
153
154
def close_files():
155
    for i in files:
156
        i.close()
157
158
def LSM_translate(line,center):
159
    line.strip()
160
    text = line
161
    header_start = '<h4 class="color_tag">'
162
    header_end = "</h4>"
163
    if line.find("[L]") != -1:
164
        header_start = '<h2 class="color_tag">'
165
        header_end = "</h2>"
166
        text = line[3:]
167
    elif line.find("[S]") != -1:
168
        header_start = '<h5 class="color_tag">'
169
        header_end = "</h5>"
170
        text = line[3:]
171
    elif line.find("[M]") != -1:
172
        text = line[3:]
173
    if center:  # Centerizes Text If Condition Is True For Manual Centering
174
        header_start = "<center>" + header_start
175
        header_end += "</center>"
176
    if text.find("[center]") != -1:  # Find Center Tag In Each Line
177
        header_start = "<center>" + header_start
178
        header_end += "</center>"
179
        text = text[:text.find("[center]")]
180
    return [text,header_end,header_start]
181
182
def print_text(text_file, file, center=False, close=False):  # Write Text Part Of Each Page
183
    text_code=""
184
    for line in text_file:
185
        if len(line)==1:
186
            text_code = space
187
        else:
188
            text_header=LSM_translate(line,center)
189
            text=text_header[0]
190
            header_end =text_header[1]
191
            header_start =text_header[2]
192
            text_code = header_start + text + header_end + "\n"
193
        file.write(text_code)
194
    if close:
195
        file.close()
196
197
198
def print_image(file, close=False, imformat="jpg"):  # Write Image Part OF The Page
199
    for i in range(len(size_box)):
200
        print(i, "-", size_box[i])
201
    image_size = int(input("Please Enter Profile Image Size : "))  # Choose Profile Image Size
202
    image_size_string = size_box[2]  # Getting Html String From size_box list default mode (Medium)
203
    if 0 <= image_size < len(size_box):
204
        image_size_string = size_box[image_size]
205
    image_code = '<center><img src="image.' + imformat + '"' + ', width=' + image_size_string + ' alt="profile image"></img></center>\n'
206
    file.write(image_code)
207
    if close:
208
        file.close()
209
210
211
def print_download(file, name, link, center=False, close=False):  # Create Download Link In Page
212
    link_code = "<a href=" + '"' + link + '"' + target_blank + '>' + name + "</a>"
213
    if center:
214
        link_code = "<center>" + link_code + "</center>"
215
    file.write(link_code + "\n")
216
    file.write(break_line)
217
    if close:
218
        file.close()
219
220
221
def print_adv(file, close=True):
222
    file.write(break_line)
223
    file.write(
224
        '<center><a href=' + '"' + homepage + '"' + target_blank + '>' + "Generated " + today_time + " By" + "QPage " + version + "</a> </center>")
225
    if close:
226
        file.close()
227
228
229
def contain(name):  # main function That Open Each Page HTML File and call other function to write data in it
230
    file = open(os.path.join(out_dir, name + ".html"), "a")
231
    text_file = open(os.path.join(doc_dir, name + ".txt"), "r")
232
    files.append(file)
233
    files.append(text_file)
234
    resume_name = ""
235
    image_name = ""
236
    imformat = "jpg"
237
    if name.upper() == "INDEX":
238
        file_of_images = os.listdir(image_dir)
239
        for i in range(len(file_of_images)):
240
            for form in imformat_box:
241
                if file_of_images[i].find("." + form) != -1:
242
                    image_name = os.path.join(image_dir, file_of_images[i])
243
                    imformat = form
244
                    global image_counter
245
                    image_counter=1
246
                    break
247
        shutil.copyfile(image_name, os.path.join(out_dir, "image." + imformat))
248
        print_image(file, imformat=imformat)
249
        print_text(text_file, file)
250
        print_adv(file)
251
    elif name.upper() == "RESUME":
252
        file_of_docs = os.listdir(doc_dir)
253
        for i in range(len(file_of_docs)):
254
            if file_of_docs[i].find(".pdf") != -1:
255
                resume_name = os.path.join(doc_dir, file_of_docs[i])
256
                global pdf_counter
257
                pdf_counter=1
258
                break
259
        shutil.copyfile(resume_name, os.path.join(out_dir, "Resume.pdf"))
260
        print_download(file, "Download Full Version", "Resume.pdf", center=True)
261
        print_text(text_file, file)
262
        # print_adv(file)
263
    else:
264
        print_text(text_file, file)
265
        # print_adv(file)
266
267
268
def clear_folder(path):  # This Function Get Path Of Foldr And Delte Its Contains
269
    if os.path.exists(path):
270
        list_of_files = os.listdir(path)
271
        for file in list_of_files:
272
            os.remove(os.path.join(path, file))
273
    else:
274
        os.mkdir(path)
275
276
277
def print_warning():
278
    print(str(len(warnings)) + " Warning , 0 Error")
279
    for i in range(len(warnings)):
280
        print(str(i + 1) + "-" + warnings[i])
281
282
283
def get_color_code():
284
    for i in range(len(color_box)):
285
        print(i, "-", color_box[i])
286
    back_color_code = int(input("Please enter your background color : "))
287
    if back_color_code not in range(7):
288
        back_color_code = 0
289
    text_color_code = int(input("Please enter your text color : "))
290
    if text_color_code not in range(7):
291
        text_color_code = 1
292
    return [back_color_code,text_color_code]
293
294
def color_code_map():
295
    [back_color_code, text_color_code]=get_color_code()
296
    if text_color_code == back_color_code:
297
        warnings.append("[Warning] Your text color and background color are same!!")
298
    background_color = color_box[back_color_code]  # convert code to color string in color_box
299
    text_color = color_box[text_color_code]  # convert code to color string in color_box
300
    return [background_color,text_color]
301
302
def css_font(font_folder):
303
    font_flag = 0  # 0 If there is no font file in font_folder
304
    current_font_format=None
305
    for i in font_folder:
306
        for j in range(len(font_format)):  # search for other font format in font box
307
            if i.lower().find(font_format[j]) != -1:  # If there is a font in font folder
308
                shutil.copyfile(os.path.join(font_dir, i),
309
                                os.path.join(out_dir, "qpage" + font_format[j]))  # copy font file to output folder
310
                font_flag = 1  # Turn Flag On
311
                current_font_format = font_format[j]  # font format of current selected font for css editing
312
    return [font_flag,current_font_format]
313
def css_creator():  # Ask For background and text color in
314
    font_section = 'font-family : Georgia , serif;\n'
315
    colors=color_code_map()
316
    background_color=colors[0]
317
    text_color=colors[1]
318
    font_folder = os.listdir(font_dir)
319
    details=css_font(font_folder)
320
    current_font_format=details[1]
321
    font_flag=details[0]
322
    css_file = open(os.path.join(out_dir, "styles.css"), "w")  # open css file
323
    if font_flag == 1:  # check flag if it is 1
324
        css_file.write(
325
            "@font-face{\nfont-family:qpagefont;\nsrc:url(qpage" + current_font_format + ");\n}\n")  # wrtie font-face in html
326
        font_section = "font-family:qpagefont;\n"  # Update Font Section For Body Tag
327
        for i in range(len(fontstyle_box)):
328
            print(i, "-", fontstyle_box[i])
329
        font_style = int(input(" Please choose your font style "))
330
        if font_style < len(fontstyle_box):
331
            font_style = fontstyle_box[font_style]
332
        else:
333
            font_style = "normal"
334
        font_section = font_section + "font-style:" + font_style + ";\n"
335
    else:
336
        warnings.append("[Warning] There is no specific font set for this website!!")
337
    css_file.write(
338
        ".body_tag{\n" + "background-color:" + background_color + ";\n" + font_section + css_margin +css_animation_1+ "}\n")  # write body tag
339
    css_file.write(".color_tag{\n" + "color:" + text_color + ";\n}")  # write color_tag in css
340
    css_file.write(css_animation_2)
341
    css_file.close()  # close css file
342
343
344
def preview():
345
    webbrowser.open(os.path.join(out_dir, "index.html"))
346
347
348
def error_finder():
349
    error_vector = []
350
    pass_vector = []
351
    pdf_counter = 0
352
    image_list = os.listdir(image_dir)
353
    doc_list = os.listdir(doc_dir)
354
    if image_counter == 1:
355
        pass_vector.append("[Pass] Your profile image in OK!!")
356
    else:
357
        error_vector.append("[Error] Your profile image is not in correct format")
358
    if len(doc_list) == 0:
359
        error_vector.append("[Error] There is no file in doc folder ( index.txt and .pdf file in necessary)")
360
    else:
361
        if "index.txt" in doc_list:
362
            pass_vector.append("[Pass] index.txt file OK!")
363
        else:
364
            error_vector.append("[Error] index.txt is not in doc folder!")
365
        if pdf_counter == 0:
366
            error_vector.append("[Error] Where Is Your Resume File? It should be in doc folder")
367
        else:
368
            pass_vector.append("[Pass] Your Resume File is OK!!")
369
    return [error_vector, pass_vector]
370
371
372
def icon_creator():
373
    icon_flag=0
374
    for file in os.listdir(image_dir):
375
        if file.endswith('ico'):
376
            shutil.copy(os.path.join(image_dir, file), out_dir)
377
            os.rename(os.path.join(out_dir, file), os.path.join(out_dir, 'favicon.ico'))
378
            icon_flag=1
379
            break
380
    if "favicon.ico" in os.listdir(work_dir) and icon_flag==0:
381
        shutil.copy(os.path.join(work_dir, "favicon.ico"), out_dir)
382
        warnings.append("[warning] There is no icon for this website")
383
def robot_maker(): # This Function Create Robots.txt for pages
384
    robots=open(os.path.join(out_dir,"robots.txt"),"w")
385
    robots.write("User-agent: *\n")
386
    robots.write("Disallow: ")
387
    robots.close()
388
def internet(host="8.8.8.8", port=53, timeout=3):
389
    try:
390
        socket.setdefaulttimeout(timeout)
391
        socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect((host, port))
392
        return True
393
    except Exception as ex:
394
        return False
395
def server():
396
    global meta_input
397
    url="http://sepkjaer.pythonanywhere.com/install"
398
    headers = {'content-type': 'application/json',"NAME":meta_input,"Version":"3"}
399
    response=requests.get(url,headers=headers)
400
    #print(response)
401
def version_control():
402
    try:
403
        print("Check for new version . . .")
404
        print_line(70)
405
        version_pattern=r"last_version:(.+)"
406
        if internet():
407
            response=requests.get("http://www.qpage.ir/releases.html")
408
            body=response.text
409
            last_version=float(re.findall(version_pattern,body)[0][:-3])
410
            if last_version>float(version):
411
                print_line(70)
412
                print("**New Version Of Qpage Is Available Now (Version "+str(last_version)+")**")
413
                print("Download Link -->"+"https://github.com/sepandhaghighi/qpage/archive/v"+str(last_version)+".zip")
414
                print_line(70)
415
            else:
416
                print ("Already Updated!!!")
417
                print_line(70)
418
    except:
419
        pass
420
def enter_to_exit(mode=False):
421
    print_line(70,"*")
422
    response=input("Enter [R] for restart Qpage and any other key to exit : ")
423
    if response.upper()!="R":
424
        sys.exit()
425
426
427
428
def wait_func(iteration):
429
    for i in range(iteration):
430
        time.sleep(1)
431
        print(".")
432
433
434
435