Advertisement
Guest User

Weather Script

a guest
Dec 30th, 2020
358
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.95 KB | None | 0 0
  1. const DEV_MODE = true //for developer only
  2. const DEV_PREVIEW = "medium" //for developer only (this script is specialy made for a medium sized widget)
  3. // !!NEW USER INPUT REQUIRED!!
  4. const API_KEY = "" // enter your openweathermap.com api key
  5. const FORECAST_DAYS = "3"
  6. const UNITS = "metric" //metric for celsius and imperial for Fahrenheit
  7. const stackSize = new Size(0, 65) //0 means its automatic
  8. const widgetBackground = new Color("#161716") //Widget Background
  9. const stackBackground = new Color("#222224") //Smaller Container Background
  10.  
  11. ////// CREATE WIDGET
  12. if (config.runsInWidget || DEV_MODE) {
  13.  
  14. const date = new Date()
  15. const dateNow = Date.now()
  16.  
  17. let df_Name = new DateFormatter()
  18. let df_Month = new DateFormatter()
  19. df_Name.dateFormat = "EEEE"
  20. df_Month.dateFormat = "MMMM"
  21.  
  22. const dayName = df_Name.string(date)
  23. const dayNumber = date.getDate().toString()
  24. const monthName = df_Month.string(date)
  25.  
  26. // let loc = await Location.current()
  27. // let lat = loc["latitude"]
  28. // let lon = loc["longitude"]
  29.  
  30. let lat = ""
  31. let lon = ""
  32.  
  33. const weatherURL = `https://api.openweathermap.org/data/2.5/onecall?lat=${lat}&lon=${lon}&exclude=current,minutely,alerts&units=${UNITS}&appid=${API_KEY}`
  34. const weatherRequest = new Request(weatherURL)
  35. const weatherData = await weatherRequest.loadJSON()
  36.  
  37. const dailyForecasts = weatherData.daily
  38. let dailyNextForecasts = []
  39.  
  40. for (const dailyForecast of dailyForecasts) {
  41. if (dailyNextForecasts.length == FORECAST_DAYS) {
  42. break
  43. }
  44. let dt = removeDigits(dateNow, 3)
  45. if (dailyForecast.dt >= dt) {
  46. dailyNextForecasts.push(dailyForecast)
  47. }
  48. }
  49. let widget = new ListWidget()
  50. widget.backgroundColor = widgetBackground
  51. widget.setPadding(10, 10, 10, 10)
  52.  
  53. //Top Row (Date & Weather)
  54. let topRow = widget.addStack()
  55. topRow.layoutHorizontally()
  56.  
  57. //Top Row Date
  58. let dateStack = topRow.addStack()
  59. dateStack.layoutHorizontally()
  60. dateStack.centerAlignContent()
  61. dateStack.setPadding(7, 7, 7, 7)
  62. dateStack.backgroundColor = stackBackground
  63. dateStack.cornerRadius = 12
  64. dateStack.size = stackSize
  65.  
  66. dateStack.addSpacer()
  67.  
  68. let dayNumberTxt = dateStack.addText(dayNumber)
  69. dayNumberTxt.font = Font.semiboldSystemFont(32)
  70. dayNumberTxt.textColor = Color.white()
  71.  
  72. dateStack.addSpacer(7)
  73.  
  74. let dateTextStack = dateStack.addStack()
  75. dateTextStack.layoutVertically()
  76.  
  77. let monthNameTxt = dateTextStack.addText(monthName.toUpperCase())
  78. monthNameTxt.font = Font.boldSystemFont(10)
  79. monthNameTxt.textColor = Color.white()
  80.  
  81. let dayNameTxt = dateTextStack.addText(dayName.toUpperCase())
  82. dayNameTxt.font = Font.semiboldSystemFont(10)
  83. dayNameTxt.textColor = calendarColor
  84.  
  85. dateStack.addSpacer()
  86.  
  87. topRow.addSpacer()
  88. widget.addSpacer()
  89.  
  90. // Top Row Daily Weather
  91. let dailyWeatherStack = topRow.addStack()
  92. dailyWeatherStack.layoutHorizontally()
  93. dailyWeatherStack.setPadding(8, 2, 8, 2)
  94. dailyWeatherStack.backgroundColor = stackBackground
  95. dailyWeatherStack.cornerRadius = 12
  96. dailyWeatherStack.size = stackSize
  97. dailyWeatherStack.centerAlignContent()
  98.  
  99. for (const nextForecast of dailyNextForecasts) {
  100.  
  101. dailyWeatherStack.addSpacer()
  102.  
  103. let dayStack = dailyWeatherStack.addStack()
  104. dayStack.layoutVertically()
  105. dayStack.centerAlignContent()
  106.  
  107. let hourStack =
  108. dayStack.addStack()
  109. hourStack.layoutHorizontally()
  110. hourStack.centerAlignContent()
  111. let hourTxt = hourStack.addText(formatDay(nextForecast.dt))
  112. hourTxt.font = Font.mediumRoundedSystemFont(9)
  113. hourTxt.textColor = Color.white()
  114.  
  115. dayStack.addSpacer(5)
  116. let iconStack =
  117. dayStack.addStack()
  118. iconStack.layoutHorizontally()
  119. tempStack.centerAlignContent()
  120. const condition = nextForecast.weather[0].id
  121. let weatherIcon = iconStack.addImage(addSFS(condition))
  122. weatherIcon.imageSize = new Size(16, 16)
  123. dayStack.addSpacer(5)
  124.  
  125. let tempStack =
  126. dayStack.addStack()
  127. tempStack.layoutHorizontally()
  128. tempStack.centerAlignContent()
  129. let tempTxt = tempStack.addText(Math.round(nextForecast.temp.max) + "°C")
  130. tempTxt.font = Font.mediumRoundedSystemFont(9)
  131. tempTxt.textColor = Color.white()
  132. }
  133.  
  134. dailyWeatherStack.addSpacer()
  135.  
  136. // SFSymbol function
  137. function addSFS(cond) {
  138. let symbols = {
  139. // Thunderstorm
  140. "2": function () {
  141. return "cloud.bolt.rain.fill"
  142. },
  143. // Drizzle
  144. "3": function () {
  145. return "cloud.drizzle.fill"
  146. },
  147. // Rain
  148. "5": function () {
  149. return (cond == 511) ? "cloud.sleet.fill" : "cloud.rain.fill"
  150. },
  151. // Snow
  152. "6": function () {
  153. return (cond >= 611 && cond <= 613) ? "cloud.snow.fill" : "snow"
  154. },
  155. // Atmosphere
  156. "7": function () {
  157. if (cond == 781) {
  158. return "tornado"
  159. }
  160. if (cond == 701 || cond == 741) {
  161. return "cloud.fog.fill"
  162. }
  163. return "sun.haze.fill"
  164. },
  165. // Clear and clouds
  166. "8": function () {
  167. if (cond == 800) {
  168. return "sun.max.fill"
  169. }
  170. if (cond == 802 || cond == 803) {
  171. return "cloud.sun.fill"
  172. }
  173. return "cloud.fill"
  174. }
  175. }
  176. // Get first condition digit.
  177. let conditionDigit = Math.floor(cond / 100)
  178. // Style and return the symbol.
  179. let sfs = SFSymbol.named(symbols[conditionDigit]())
  180. sfs.applyFont(Font.systemFont(25))
  181. return sfs.image
  182. }
  183.  
  184. Script.setWidget(widget)
  185.  
  186. if (DEV_MODE) {
  187. if (DEV_PREVIEW == "small") {
  188. widget.presentSmall()
  189. }
  190. if (DEV_PREVIEW == "medium") {
  191. widget.presentMedium()
  192. }
  193. if (DEV_PREVIEW == "large") {
  194. widget.presentLarge()
  195. }
  196. }
  197.  
  198. Script.complete()
  199. }
  200.  
  201. ////// FUNCTIONS
  202.  
  203. function removeDigits(x, n) {
  204. return (x - (x % Math.pow(10, n))) / Math.pow(10, n)
  205. }
  206.  
  207. function formatHours(UNIX_timestamp) {
  208.  
  209. var date = new Date(UNIX_timestamp * 1000)
  210. var hours = date.getHours()
  211.  
  212. var ampm = hours >= 12 ? ' PM' : ' AM'
  213. hours = hours % 12
  214. hours = hours ? hours : 12
  215. var strTime = hours.toString() + ampm
  216.  
  217. return strTime
  218. }
  219.  
  220. function formatDay(UNIX_timestamp) {
  221.  
  222. var date = new Date(UNIX_timestamp * 1000)
  223. var day = date.getDay()
  224. var dayStr = ""
  225.  
  226. switch (day) {
  227. case (0):
  228. dayStr = "SUN"
  229. break
  230. case (1):
  231. dayStr = "MON"
  232. break
  233. case (2):
  234. dayStr = "TUE"
  235. break
  236. case (3):
  237. dayStr = "WED"
  238. break
  239. case (4):
  240. dayStr = "THU"
  241. break
  242. case (5):
  243. dayStr = "FRI"
  244. break
  245. case (6):
  246. dayStr = "SAT"
  247. break
  248. }
  249.  
  250. return dayStr
  251. }
  252.  
  253. function formatTime(date) {
  254. let df = new DateFormatter()
  255. df.useNoDateStyle()
  256. df.useShortTimeStyle()
  257. return df.string(date)
  258. }
  259.  
  260. async function getImg(image) {
  261. let fm = FileManager.iCloud()
  262. let dir = fm.documentsDirectory()
  263. let path = fm.joinPath(dir + "/imgs/weather", image)
  264. let download = await fm.downloadFileFromiCloud(path)
  265. let isDownloaded = await fm.isFileDownloaded(path)
  266.  
  267. if (fm.fileExists(path)) {
  268. return fm.readImage(path)
  269. } else {
  270. console.log("Error: File does not exist.")
  271. }
  272. }
  273.  
  274. // helper function to download an image from a given url
  275. async function loadImage(imgUrl) {
  276. const req = new Request(imgUrl)
  277. return await req.loadImage()
  278. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement