Completed
Push — master ( 2be7a1...14d712 )
by Sepand
46s
created

download_lorem()   A

Complexity

Conditions 2

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

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