CCMain.m 247 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638
  1. //
  2. // CCMain.m
  3. // Crypto Cloud Technology Nextcloud
  4. //
  5. // Created by Marino Faggiana on 04/09/14.
  6. // Copyright (c) 2017 TWS. All rights reserved.
  7. //
  8. // Author Marino Faggiana <m.faggiana@twsweb.it>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. #import "CCMain.h"
  24. #import "AppDelegate.h"
  25. #import "CCPhotos.h"
  26. #import "CCSynchronize.h"
  27. #import "CCTransfersCell.h"
  28. #import "OCActivity.h"
  29. #import "OCNotifications.h"
  30. #import "OCNotificationsAction.h"
  31. #import "OCFrameworkConstants.h"
  32. #import "OCCapabilities.h"
  33. #import "CTAssetCheckmark.h"
  34. #import "NCBridgeSwift.h"
  35. #define alertCreateFolder 1
  36. #define alertCreateFolderCrypto 2
  37. #define alertRename 3
  38. @interface CCMain () <CCActionsDeleteDelegate, CCActionsRenameDelegate, CCActionsSearchDelegate, CCActionsDownloadThumbnailDelegate, CCActionsSettingFavoriteDelegate>
  39. {
  40. tableMetadata *_metadata;
  41. BOOL _isRoot;
  42. BOOL _isViewDidLoad;
  43. BOOL _isOfflineServerUrl;
  44. BOOL _isPickerCriptate; // if is cryptated image or video back from picker
  45. BOOL _isSelectedMode;
  46. NSMutableArray *_selectedMetadatas;
  47. NSMutableArray *_queueSelector;
  48. NSUInteger _numSelectedMetadatas;
  49. UIImageView *_ImageTitleHomeCryptoCloud;
  50. UIView *_reMenuBackgroundView;
  51. UITapGestureRecognizer *_singleFingerTap;
  52. NSString *_directoryGroupBy;
  53. NSString *_directoryOrder;
  54. NSUInteger _failedAttempts;
  55. NSDate *_lockUntilDate;
  56. NSString *_fatherPermission;
  57. UIRefreshControl *_refreshControl;
  58. UIDocumentInteractionController *_docController;
  59. CCHud *_hud;
  60. CCHud *_hudDeterminate;
  61. // Datasource
  62. CCSectionDataSourceMetadata *_sectionDataSource;
  63. NSDate *_dateReadDataSource;
  64. // Search
  65. BOOL _isSearchMode;
  66. NSString *_searchFileName;
  67. NSMutableArray *_searchResultMetadatas;
  68. NSString *_depth;
  69. NSString *_noFilesSearchTitle;
  70. NSString *_noFilesSearchDescription;
  71. // Login
  72. CCLoginWeb *_loginWeb;
  73. CCLogin *_loginVC;
  74. }
  75. @end
  76. @implementation CCMain
  77. #pragma --------------------------------------------------------------------------------------------
  78. #pragma mark ===== Init =====
  79. #pragma --------------------------------------------------------------------------------------------
  80. - (id)initWithCoder:(NSCoder *)aDecoder
  81. {
  82. if (self = [super initWithCoder:aDecoder]) {
  83. _directoryOrder = [CCUtility getOrderSettings];
  84. _directoryGroupBy = [CCUtility getGroupBySettings];
  85. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(initializeMain:) name:@"initializeMain" object:nil];
  86. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clearDateReadDataSource:) name:@"clearDateReadDataSource" object:nil];
  87. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setTitle) name:@"setTitleMain" object:nil];
  88. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(triggerProgressTask:) name:@"NotificationProgressTask" object:nil];
  89. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeTheming) name:@"changeTheming" object:nil];
  90. }
  91. return self;
  92. }
  93. #pragma --------------------------------------------------------------------------------------------
  94. #pragma mark ===== View =====
  95. #pragma --------------------------------------------------------------------------------------------
  96. - (void)viewDidLoad
  97. {
  98. [super viewDidLoad];
  99. // init object
  100. _metadata = [tableMetadata new];
  101. _hud = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  102. _hudDeterminate = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  103. _selectedMetadatas = [NSMutableArray new];
  104. _queueSelector = [NSMutableArray new];
  105. _sectionDataSource = [CCSectionDataSourceMetadata new];
  106. _isViewDidLoad = YES;
  107. _fatherPermission = @"";
  108. _searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
  109. _searchResultMetadatas = [NSMutableArray new];
  110. _searchFileName = @"";
  111. _depth = @"0";
  112. _noFilesSearchTitle = @"";
  113. _noFilesSearchDescription = @"";
  114. // delegate
  115. self.tableView.delegate = self;
  116. self.tableView.tableFooterView = [UIView new];
  117. self.tableView.separatorColor = [NCBrandColor sharedInstance].seperator;
  118. self.tableView.emptyDataSetDelegate = self;
  119. self.tableView.emptyDataSetSource = self;
  120. self.searchController.delegate = self;
  121. self.searchController.searchBar.delegate = self;
  122. [[CCNetworking sharedNetworking] settingDelegate:self];
  123. // Custom Cell
  124. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMain" bundle:nil] forCellReuseIdentifier:@"CellMain"];
  125. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMainTransfer" bundle:nil] forCellReuseIdentifier:@"CellMainTransfer"];
  126. // long press recognizer TableView
  127. UILongPressGestureRecognizer* longPressRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(onLongPressTableView:)];
  128. [self.tableView addGestureRecognizer:longPressRecognizer];
  129. // Pull-to-Refresh
  130. [self createRefreshControl];
  131. // Register for 3D Touch Previewing if available
  132. if ([self.traitCollection respondsToSelector:@selector(forceTouchCapability)] && (self.traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable))
  133. {
  134. [self registerForPreviewingWithDelegate:self sourceView:self.view];
  135. }
  136. // Back Button
  137. if ([_serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:app.activeUrl]])
  138. self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"navigationLogo"] style:UIBarButtonItemStylePlain target:nil action:nil];
  139. // reMenu Background
  140. _reMenuBackgroundView = [[UIView alloc] init];
  141. _reMenuBackgroundView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
  142. // if this is not Main (the Main uses inizializeMain)
  143. if (_isRoot == NO && app.activeAccount.length > 0) {
  144. // Settings this folder & delegate & Loading datasource
  145. app.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  146. // Load Datasource
  147. [self reloadDatasource:_serverUrl fileID:nil selector:nil];
  148. // Read Folder
  149. [self readFolderWithForced:NO serverUrl:_serverUrl];
  150. }
  151. // Title
  152. [self setTitle];
  153. // Search
  154. self.definesPresentationContext = YES;
  155. self.searchController.searchResultsUpdater = self;
  156. self.searchController.dimsBackgroundDuringPresentation = NO;
  157. self.tableView.tableHeaderView = self.searchController.searchBar;
  158. self.searchController.searchBar.barTintColor = [NCBrandColor sharedInstance].seperator;
  159. [self.searchController.searchBar sizeToFit];
  160. self.searchController.searchBar.delegate = self;
  161. self.searchController.searchBar.placeholder = NSLocalizedString(@"_search_this_folder_",nil);
  162. if ([[NCManageDatabase sharedInstance] getServerVersion] >= 12) {
  163. if (_isRoot)
  164. self.searchController.searchBar.scopeButtonTitles = [NSArray arrayWithObjects:NSLocalizedString(@"_search_this_folder_",nil),NSLocalizedString(@"_search_all_folders_",nil), nil];
  165. else
  166. self.searchController.searchBar.scopeButtonTitles = [NSArray arrayWithObjects:NSLocalizedString(@"_search_this_folder_",nil),NSLocalizedString(@"_search_sub_folder_",nil), nil];
  167. } else {
  168. self.searchController.searchBar.scopeButtonTitles = nil;
  169. }
  170. // Hide Search Filed on Load
  171. [self.tableView setContentOffset:CGPointMake(0, self.searchController.searchBar.frame.size.height - self.tableView.contentOffset.y)];
  172. }
  173. // Apparirà
  174. - (void)viewWillAppear:(BOOL)animated
  175. {
  176. [super viewWillAppear:animated];
  177. // test
  178. if (app.activeAccount.length == 0)
  179. return;
  180. // Settings this folder & delegate & Loading datasource
  181. app.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  182. [[CCNetworking sharedNetworking] settingDelegate:self];
  183. // Color
  184. [app aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:_isFolderEncrypted online:[app.reachability isReachable] hidden:NO];
  185. [app aspectTabBar:self.tabBarController.tabBar hidden:NO];
  186. if (_isSelectedMode)
  187. [self setUINavigationBarSelected];
  188. else
  189. [self setUINavigationBarDefault];
  190. // Plus Button
  191. [app plusButtonVisibile:true];
  192. }
  193. // E' arrivato
  194. - (void)viewDidAppear:(BOOL)animated
  195. {
  196. [super viewDidAppear:animated];
  197. // Active Main
  198. app.activeMain = self;
  199. // Test viewDidLoad
  200. if (_isViewDidLoad) {
  201. _isViewDidLoad = NO;
  202. } else {
  203. if (app.activeAccount.length > 0) {
  204. // Load Datasource
  205. [self reloadDatasource:_serverUrl fileID:nil selector:nil];
  206. // Read Folder
  207. [self readFolderWithForced:NO serverUrl:_serverUrl];
  208. }
  209. }
  210. // Title
  211. [self setTitle];
  212. }
  213. - (void)viewWillDisappear:(BOOL)animated
  214. {
  215. [super viewWillDisappear:animated];
  216. [self closeAllMenu];
  217. }
  218. - (void)didReceiveMemoryWarning
  219. {
  220. [super didReceiveMemoryWarning];
  221. // Dispose of any resources that can be recreated.
  222. }
  223. - (BOOL)prefersStatusBarHidden
  224. {
  225. return NO;
  226. }
  227. // detect scroll for remove keyboard in search mode
  228. - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
  229. {
  230. if (_isSearchMode && scrollView == self.tableView) {
  231. [self.searchController.searchBar endEditing:YES];
  232. }
  233. }
  234. - (void)changeTheming
  235. {
  236. if (self.isViewLoaded && self.view.window)
  237. [app changeTheming:self];
  238. // Refresh control
  239. _refreshControl.tintColor = [NCBrandColor sharedInstance].brand;
  240. // Reload Table View
  241. [self.tableView reloadData];
  242. }
  243. #pragma --------------------------------------------------------------------------------------------
  244. #pragma mark ===== Initizlize Mail =====
  245. #pragma --------------------------------------------------------------------------------------------
  246. - (void)initializeMain:(NSNotification *)notification
  247. {
  248. _directoryGroupBy = nil;
  249. _directoryOrder = nil;
  250. _dateReadDataSource = nil;
  251. // test
  252. if (app.activeAccount.length == 0)
  253. return;
  254. if ([app.listMainVC count] == 0 || _isRoot) {
  255. // This is Root
  256. _isRoot = YES;
  257. // Crypto Mode
  258. if ([[CCUtility getKeyChainPasscodeForUUID:[CCUtility getUUID]] length] == 0) {
  259. app.isCryptoCloudMode = NO;
  260. } else {
  261. app.isCryptoCloudMode = YES;
  262. }
  263. // go Home
  264. [self.navigationController popToRootViewControllerAnimated:NO];
  265. // Remove search mode
  266. [self cancelSearchBar];
  267. _serverUrl = [CCUtility getHomeServerUrlActiveUrl:app.activeUrl];
  268. _isFolderEncrypted = NO;
  269. app.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  270. // add list
  271. [app.listMainVC setObject:self forKey:_serverUrl];
  272. // setting Networking
  273. [[CCNetworking sharedNetworking] settingDelegate:self];
  274. [[CCNetworking sharedNetworking] settingAccount];
  275. // populate shared Link & User variable
  276. NSArray *results = [[NCManageDatabase sharedInstance] getShares];
  277. if (results) {
  278. app.sharesLink = results[0];
  279. app.sharesUserAndGroup = results[1];
  280. }
  281. // Setting Theming
  282. [app settingThemingColorBrand];
  283. // Load Datasource
  284. [self reloadDatasource:_serverUrl fileID:nil selector:nil];
  285. // Load Folder
  286. [self readFolderWithForced:NO serverUrl:_serverUrl];
  287. // Load photo datasorce
  288. if (app.activePhotos)
  289. [app.activePhotos reloadDatasourceForced];
  290. // remove all of detail
  291. if (app.activeDetail)
  292. [app.activeDetail removeAllView];
  293. // remove all Notification Messages
  294. [app.listOfNotifications removeAllObjects];
  295. // home main
  296. app.homeMain = self;
  297. // Initializations
  298. [app applicationInitialized];
  299. } else {
  300. // reload datasource
  301. [self reloadDatasource:_serverUrl fileID:nil selector:nil];
  302. }
  303. }
  304. #pragma --------------------------------------------------------------------------------------------
  305. #pragma mark ==== DZNEmptyDataSetSource ====
  306. #pragma --------------------------------------------------------------------------------------------
  307. /*
  308. - (BOOL)emptyDataSetShouldDisplay:(UIScrollView *)scrollView
  309. {
  310. if(_isSearchMode)
  311. return NO;
  312. else
  313. return YES;
  314. }
  315. */
  316. - (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView
  317. {
  318. return YES;
  319. }
  320. - (UIColor *)backgroundColorForEmptyDataSet:(UIScrollView *)scrollView
  321. {
  322. return [UIColor whiteColor];
  323. }
  324. - (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView
  325. {
  326. if (_isSearchMode)
  327. return [UIImage imageNamed:@"searchBig"];
  328. else
  329. return [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"filesNoFiles"] color:[NCBrandColor sharedInstance].brand];
  330. }
  331. - (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
  332. {
  333. NSString *text;
  334. if (_isSearchMode)
  335. text = _noFilesSearchTitle;
  336. else
  337. text = [NSString stringWithFormat:@"%@", NSLocalizedString(@"_files_no_files_", nil)];
  338. NSDictionary *attributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:20.0f], NSForegroundColorAttributeName:[UIColor lightGrayColor]};
  339. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  340. }
  341. - (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView
  342. {
  343. NSString *text;
  344. if (_isSearchMode)
  345. text = _noFilesSearchDescription;
  346. else
  347. text = [NSString stringWithFormat:@"\n%@", NSLocalizedString(@"_no_file_pull_down_", nil)];
  348. NSMutableParagraphStyle *paragraph = [NSMutableParagraphStyle new];
  349. paragraph.lineBreakMode = NSLineBreakByWordWrapping;
  350. paragraph.alignment = NSTextAlignmentCenter;
  351. NSDictionary *attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:14.0], NSForegroundColorAttributeName: [UIColor lightGrayColor], NSParagraphStyleAttributeName: paragraph};
  352. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  353. }
  354. #pragma --------------------------------------------------------------------------------------------
  355. #pragma mark ===== AlertView =====
  356. #pragma --------------------------------------------------------------------------------------------
  357. - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
  358. {
  359. [alertView dismissWithClickedButtonIndex:buttonIndex animated:YES];
  360. if (alertView.tag == alertCreateFolder && buttonIndex == 1) [self createFolder:[alertView textFieldAtIndex:0].text autoUploadDirectory:NO];
  361. if (alertView.tag == alertCreateFolderCrypto && buttonIndex == 1) [self createFolderEncrypted:[alertView textFieldAtIndex:0].text];
  362. if (alertView.tag == alertRename && buttonIndex == 1) {
  363. if ([_metadata.model isEqualToString:@"note"]) {
  364. [self renameNote:_metadata fileName:[alertView textFieldAtIndex:0].text];
  365. } else {
  366. [self renameFile:_metadata fileName:[alertView textFieldAtIndex:0].text];
  367. }
  368. }
  369. }
  370. // accept only number char > 0
  371. - (BOOL)alertViewShouldEnableFirstOtherButton:(UIAlertView *)alertView
  372. {
  373. /* Retrieve a text field at an index -
  374. raises NSRangeException when textFieldIndex is out-of-bounds.
  375. The field at index 0 will be the first text field
  376. (the single field or the login field),
  377. The field at index 1 will be the password field. */
  378. /*
  379. 1> Get the Text Field in alertview
  380. 2> Get the text of that Text Field
  381. 3> Verify that text length
  382. 4> return YES or NO Based on the length
  383. */
  384. return ([[[alertView textFieldAtIndex:0] text] length]>0)?YES:NO;
  385. }
  386. #pragma --------------------------------------------------------------------------------------------
  387. #pragma mark ===== Graphic Window =====
  388. #pragma --------------------------------------------------------------------------------------------
  389. - (void)createRefreshControl
  390. {
  391. _refreshControl = [UIRefreshControl new];
  392. _refreshControl.tintColor = [NCBrandColor sharedInstance].brand;
  393. _refreshControl.backgroundColor = [UIColor colorWithRed:235.0/255.0 green:235.0/255.0 blue:235.0/255.0 alpha:1.0];
  394. [_refreshControl addTarget:self action:@selector(refreshControlTarget) forControlEvents:UIControlEventValueChanged];
  395. [self setRefreshControl:_refreshControl];
  396. }
  397. - (void)deleteRefreshControl
  398. {
  399. [_refreshControl endRefreshing];
  400. self.refreshControl = nil;
  401. }
  402. - (void)refreshControlTarget
  403. {
  404. [self readFolderWithForced:YES serverUrl:_serverUrl];
  405. // Actuate `Peek` feedback (weak boom)
  406. AudioServicesPlaySystemSound(1519);
  407. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:NO];
  408. }
  409. - (void)setTitle
  410. {
  411. // Color text self.navigationItem.title
  412. [app aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:_isFolderEncrypted online:[app.reachability isReachable] hidden:NO];
  413. if (_isSelectedMode) {
  414. NSUInteger totali = [_sectionDataSource.allRecordsDataSource count];
  415. NSUInteger selezionati = [[self.tableView indexPathsForSelectedRows] count];
  416. self.navigationItem.titleView = nil;
  417. self.navigationItem.title = [NSString stringWithFormat:@"%@ : %lu / %lu", NSLocalizedString(@"_selected_", nil), (unsigned long)selezionati, (unsigned long)totali];
  418. } else {
  419. // we are in home : LOGO BRAND
  420. if ([_serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:app.activeUrl]]) {
  421. self.navigationItem.title = nil;
  422. if ([app.reachability isReachable] == NO)
  423. _ImageTitleHomeCryptoCloud = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"navigationLogoOffline"]];
  424. else
  425. _ImageTitleHomeCryptoCloud = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"navigationLogo"]];
  426. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  427. UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(menuLogo)];
  428. [singleTap setNumberOfTapsRequired:1];
  429. [_ImageTitleHomeCryptoCloud addGestureRecognizer:singleTap];
  430. self.navigationItem.titleView = _ImageTitleHomeCryptoCloud;
  431. } else {
  432. self.navigationItem.title = _titleMain;
  433. }
  434. }
  435. }
  436. - (void)setUINavigationBarDefault
  437. {
  438. [app aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:_isFolderEncrypted online:[app.reachability isReachable] hidden:NO];
  439. UIBarButtonItem *buttonMore, *buttonNotification;
  440. // =
  441. buttonMore = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"navigationControllerMenu"] style:UIBarButtonItemStylePlain target:self action:@selector(toggleReMainMenu)];
  442. buttonMore.enabled = true;
  443. // <
  444. self.navigationController.navigationBar.hidden = NO;
  445. // Notification
  446. if ([app.listOfNotifications count] > 0) {
  447. buttonNotification = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"notification"] style:UIBarButtonItemStylePlain target:self action:@selector(viewNotification)];
  448. buttonNotification.tintColor = [NCBrandColor sharedInstance].navigationBarText;
  449. buttonNotification.enabled = true;
  450. }
  451. if (buttonNotification)
  452. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, buttonNotification, nil];
  453. else
  454. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, nil];
  455. self.navigationItem.leftBarButtonItem = nil;
  456. }
  457. - (void)setUINavigationBarSelected
  458. {
  459. [app aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:_isFolderEncrypted online:[app.reachability isReachable] hidden:NO];
  460. UIImage *icon = [UIImage imageNamed:@"navigationControllerMenu"];
  461. UIBarButtonItem *buttonMore = [[UIBarButtonItem alloc] initWithImage:icon style:UIBarButtonItemStylePlain target:self action:@selector(toggleReSelectMenu)];
  462. UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIBarButtonItemStylePlain target:self action:@selector(cancelSelect)];
  463. self.navigationItem.leftBarButtonItem = leftButton;
  464. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, nil];
  465. }
  466. - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
  467. {
  468. [self closeAllMenu];
  469. [coordinator animateAlongsideTransition:nil completion:^(id<UIViewControllerTransitionCoordinatorContext> context) {
  470. }];
  471. [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
  472. }
  473. - (void)cancelSelect
  474. {
  475. [self tableViewSelect:NO];
  476. [app.reSelectMenu close];
  477. }
  478. - (void)closeAllMenu
  479. {
  480. // close Menu
  481. [app.reSelectMenu close];
  482. [app.reMainMenu close];
  483. // Close Menu Logo
  484. [CCMenuAccount dismissMenu];
  485. }
  486. #pragma --------------------------------------------------------------------------------------------
  487. #pragma mark ===== Document Picker =====
  488. #pragma --------------------------------------------------------------------------------------------
  489. - (void)documentMenuWasCancelled:(UIDocumentMenuViewController *)documentMenu
  490. {
  491. NSLog(@"Cancelled");
  492. }
  493. - (void)documentPickerWasCancelled:(UIDocumentPickerViewController *)controller
  494. {
  495. NSLog(@"Cancelled");
  496. }
  497. - (void)documentMenu:(UIDocumentMenuViewController *)documentMenu didPickDocumentPicker:(UIDocumentPickerViewController *)documentPicker
  498. {
  499. documentPicker.delegate = self;
  500. [self presentViewController:documentPicker animated:YES completion:nil];
  501. }
  502. - (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url
  503. {
  504. if (controller.documentPickerMode == UIDocumentPickerModeImport) {
  505. NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] initWithFilePresenter:nil];
  506. __block NSError *error;
  507. [coordinator coordinateReadingItemAtURL:url options:NSFileCoordinatorReadingForUploading error:&error byAccessor:^(NSURL *newURL) {
  508. NSString *fileName = [url lastPathComponent];
  509. NSString *fileNamePath = [NSString stringWithFormat:@"%@/%@", app.directoryUser, fileName];
  510. NSData *data = [NSData dataWithContentsOfURL:newURL];
  511. if (data && error == nil) {
  512. if ([data writeToFile:fileNamePath options:NSDataWritingAtomic error:&error]) {
  513. // Upload File
  514. [[CCNetworking sharedNetworking] uploadFile:fileName serverUrl:_serverUrl cryptated:_isPickerCriptate onlyPlist:NO session:k_upload_session taskStatus: k_taskStatusResume selector:nil selectorPost:nil errorCode:0 delegate:nil];
  515. } else {
  516. [app messageNotification:@"_error_" description:error.description visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  517. }
  518. } else {
  519. [app messageNotification:@"_error_" description:@"_read_file_error_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  520. }
  521. }];
  522. }
  523. }
  524. - (void)openImportDocumentPicker
  525. {
  526. UIDocumentMenuViewController *documentProviderMenu = [[UIDocumentMenuViewController alloc] initWithDocumentTypes:@[@"public.data"] inMode:UIDocumentPickerModeImport];
  527. documentProviderMenu.modalPresentationStyle = UIModalPresentationFormSheet;
  528. documentProviderMenu.popoverPresentationController.sourceView = self.view;
  529. documentProviderMenu.popoverPresentationController.sourceRect = self.view.bounds;
  530. documentProviderMenu.delegate = self;
  531. [self presentViewController:documentProviderMenu animated:YES completion:nil];
  532. }
  533. #pragma --------------------------------------------------------------------------------------------
  534. #pragma mark ===== Assets Picker =====
  535. #pragma --------------------------------------------------------------------------------------------
  536. - (void)openAssetsPickerController
  537. {
  538. CTAssetCheckmark *checkmark = [CTAssetCheckmark appearance];
  539. checkmark.tintColor = [NCBrandColor sharedInstance].brand;
  540. [checkmark setMargin:0.0 forVerticalEdge:NSLayoutAttributeRight horizontalEdge:NSLayoutAttributeTop];
  541. UINavigationBar *navBar = [UINavigationBar appearanceWhenContainedIn:[CTAssetsPickerController class], nil];
  542. [app aspectNavigationControllerBar:navBar encrypted:NO online:YES hidden:NO];
  543. [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status){
  544. dispatch_async(dispatch_get_main_queue(), ^{
  545. // init picker
  546. CTAssetsPickerController *picker = [[CTAssetsPickerController alloc] init];
  547. // set delegate
  548. picker.delegate = self;
  549. // to show selection order
  550. //picker.showsSelectionIndex = YES;
  551. // to present picker as a form sheet in iPad
  552. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  553. picker.modalPresentationStyle = UIModalPresentationFormSheet;
  554. // present picker
  555. [self presentViewController:picker animated:YES completion:nil];
  556. });
  557. }];
  558. }
  559. - (void)assetsPickerController:(CTAssetsPickerController *)picker didFinishPickingAssets:(NSMutableArray *)assets
  560. {
  561. [picker dismissViewControllerAnimated:YES completion:^{
  562. CreateFormUploadAssets *form = [[CreateFormUploadAssets alloc] init:_titleMain serverUrl:_serverUrl assets:assets cryptated:_isPickerCriptate session:k_upload_session];
  563. form.title = NSLocalizedString(@"_upload_photos_videos_", nil);
  564. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:form];
  565. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  566. [self presentViewController:navigationController animated:YES completion:nil];
  567. }];
  568. }
  569. #pragma --------------------------------------------------------------------------------------------
  570. #pragma mark ===== UIDocumentInteractionControllerDelegate =====
  571. #pragma --------------------------------------------------------------------------------------------
  572. - (void)documentInteractionControllerDidDismissOptionsMenu:(UIDocumentInteractionController *)controller
  573. {
  574. // evitiamo il rimando della eventuale photo e/o video
  575. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  576. if (tableAccount.autoUpload) {
  577. [[NCManageDatabase sharedInstance] setAccountAutoUploadDateAssetType:PHAssetMediaTypeImage assetDate:[NSDate date]];
  578. [[NCManageDatabase sharedInstance] setAccountAutoUploadDateAssetType:PHAssetMediaTypeVideo assetDate:[NSDate date]];
  579. }
  580. }
  581. #pragma --------------------------------------------------------------------------------------------
  582. #pragma mark ===== UnZipFile =====
  583. #pragma --------------------------------------------------------------------------------------------
  584. - (void)unZipFile:(NSString *)fileID
  585. {
  586. [_hudDeterminate visibleHudTitle:NSLocalizedString(@"_unzip_in_progress_", nil) mode:MBProgressHUDModeDeterminate color:nil];
  587. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  588. NSString *fileZip = [NSString stringWithFormat:@"%@/%@", app.directoryUser, fileID];
  589. [SSZipArchive unzipFileAtPath:fileZip toDestination:[CCUtility getDirectoryLocal] overwrite:YES password:nil progressHandler:^(NSString *entry, unz_file_info zipInfo, long entryNumber, long total) {
  590. dispatch_async(dispatch_get_main_queue(), ^{
  591. float progress = (float) entryNumber / (float)total;
  592. [_hudDeterminate progress:progress];
  593. });
  594. } completionHandler:^(NSString *path, BOOL succeeded, NSError *error) {
  595. dispatch_async(dispatch_get_main_queue(), ^{
  596. [_hudDeterminate hideHud];
  597. if (succeeded) [app messageNotification:@"_info_" description:@"_file_unpacked_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess errorCode:0];
  598. else [app messageNotification:@"_error_" description:[NSString stringWithFormat:@"Error %ld", (long)error.code] visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  599. });
  600. }];
  601. });
  602. }
  603. #pragma --------------------------------------------------------------------------------------------
  604. #pragma mark ===== Create New (OpenModel) =====
  605. #pragma --------------------------------------------------------------------------------------------
  606. - (void)openModel:(NSString *)tipo isNew:(BOOL)isnew
  607. {
  608. UIViewController *viewController;
  609. NSString *fileName, *uuid, *fileID, *serverUrl;
  610. NSIndexPath * index = [self.tableView indexPathForSelectedRow];
  611. [self.tableView deselectRowAtIndexPath:index animated:NO];
  612. if (isnew) {
  613. fileName = nil;
  614. uuid = [CCUtility getUUID];
  615. fileID = nil;
  616. serverUrl = _serverUrl;
  617. } else {
  618. fileName = _metadata.fileName;
  619. uuid = _metadata.uuid;
  620. fileID = _metadata.fileID;
  621. serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  622. }
  623. if ([tipo isEqualToString:@"cartadicredito"])
  624. viewController = [[CCCartaDiCredito alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  625. if ([tipo isEqualToString:@"bancomat"])
  626. viewController = [[CCBancomat alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  627. if ([tipo isEqualToString:@"contocorrente"])
  628. viewController = [[CCContoCorrente alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  629. if ([tipo isEqualToString:@"accountweb"])
  630. viewController = [[CCAccountWeb alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  631. if ([tipo isEqualToString:@"patenteguida"])
  632. viewController = [[CCPatenteGuida alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  633. if ([tipo isEqualToString:@"cartaidentita"])
  634. viewController = [[CCCartaIdentita alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  635. if ([tipo isEqualToString:@"passaporto"])
  636. viewController = [[CCPassaporto alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  637. if ([tipo isEqualToString:@"note"]) {
  638. viewController = [[CCNote alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  639. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  640. [self presentViewController:navigationController animated:YES completion:nil];
  641. } else {
  642. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  643. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  644. [self presentViewController:navigationController animated:YES completion:nil];
  645. }
  646. }
  647. // New folder or new photo or video
  648. - (void)returnCreate:(NSInteger)type
  649. {
  650. switch (type) {
  651. /* PLAIN */
  652. case k_returnCreateFolderPlain: {
  653. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_create_folder_",nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"_cancel_",nil) otherButtonTitles:NSLocalizedString(@"_save_", nil), nil];
  654. [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
  655. alertView.tag = alertCreateFolder;
  656. [alertView show];
  657. }
  658. break;
  659. case k_returnCreateFotoVideoPlain: {
  660. _isPickerCriptate = false;
  661. [self openAssetsPickerController];
  662. }
  663. break;
  664. case k_returnCreateFilePlain: {
  665. _isPickerCriptate = false;
  666. [self openImportDocumentPicker];
  667. }
  668. break;
  669. /* ENCRYPTED */
  670. case k_returnCreateFolderEncrypted: {
  671. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_create_folder_",nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"_cancel_",nil) otherButtonTitles:NSLocalizedString(@"_save_", nil), nil];
  672. [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
  673. alertView.tag = alertCreateFolderCrypto;
  674. [alertView show];
  675. }
  676. break;
  677. case k_returnCreateFotoVideoEncrypted: {
  678. _isPickerCriptate = true;
  679. [self openAssetsPickerController];
  680. }
  681. break;
  682. case k_returnCreateFileEncrypted: {
  683. _isPickerCriptate = true;
  684. [self openImportDocumentPicker];
  685. }
  686. break;
  687. /* UTILITY */
  688. case k_returnNote:
  689. [self openModel:@"note" isNew:true];
  690. break;
  691. case k_returnAccountWeb:
  692. [self openModel:@"accountweb" isNew:true];
  693. break;
  694. /* BANK */
  695. case k_returnCartaDiCredito:
  696. [self openModel:@"cartadicredito" isNew:true];
  697. break;
  698. case k_returnBancomat:
  699. [self openModel:@"bancomat" isNew:true];
  700. break;
  701. case k_returnContoCorrente:
  702. [self openModel:@"contocorrente" isNew:true];
  703. break;
  704. /* DOCUMENT */
  705. case k_returnPatenteGuida:
  706. [self openModel:@"patenteguida" isNew:true];
  707. break;
  708. case k_returnCartaIdentita:
  709. [self openModel:@"cartaidentita" isNew:true];
  710. break;
  711. case k_returnPassaporto:
  712. [self openModel:@"passaporto" isNew:true];
  713. break;
  714. }
  715. }
  716. #pragma --------------------------------------------------------------------------------------------
  717. #pragma mark ===== Save selected File =====
  718. #pragma --------------------------------------------------------------------------------------------
  719. -(void)saveSelectedFilesSelector:(NSString *)path didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
  720. {
  721. if (error)
  722. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  723. else
  724. [app messageNotification:@"_save_selected_files_" description:@"_file_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess errorCode:error.code];
  725. }
  726. - (void)saveSelectedFiles
  727. {
  728. NSLog(@"[LOG] Start download selected files ...");
  729. [_hud visibleHudTitle:@"" mode:MBProgressHUDModeIndeterminate color:nil];
  730. NSArray *metadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  731. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  732. for (tableMetadata *metadata in metadatas) {
  733. if (metadata.directory == NO && [metadata.type isEqualToString: k_metadataType_file] && ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])) {
  734. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  735. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorSave selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  736. }
  737. }
  738. [_hud hideHud];
  739. });
  740. [self tableViewSelect:NO];
  741. }
  742. #pragma --------------------------------------------------------------------------------------------
  743. #pragma mark ===== Change Password =====
  744. #pragma --------------------------------------------------------------------------------------------
  745. - (void) loginSuccess:(NSInteger)loginType
  746. {
  747. [self readFolderWithForced:YES serverUrl:_serverUrl];
  748. }
  749. - (void)changePasswordAccount
  750. {
  751. // Brand
  752. if ([NCBrandOptions sharedInstance].use_login_web) {
  753. _loginWeb = [CCLoginWeb new];
  754. _loginWeb.delegate = self;
  755. _loginWeb.loginType = loginModifyPasswordUser;
  756. dispatch_async(dispatch_get_main_queue(), ^ {
  757. [_loginWeb presentModalWithDefaultTheme:self];
  758. });
  759. } else {
  760. _loginVC = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"CCLoginNextcloud"];
  761. _loginVC.delegate = self;
  762. _loginVC.loginType = loginModifyPasswordUser;
  763. [self presentViewController:_loginVC animated:YES completion:nil];
  764. }
  765. }
  766. #pragma mark -
  767. #pragma --------------------------------------------------------------------------------------------
  768. #pragma mark ===== Peek & Pop =====
  769. #pragma --------------------------------------------------------------------------------------------
  770. - (UIViewController *)previewingContext:(id<UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location
  771. {
  772. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  773. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  774. if (metadata.thumbnailExists && !metadata.cryptated) {
  775. CCCellMain *cell = [self.tableView cellForRowAtIndexPath:indexPath];
  776. if (cell) {
  777. previewingContext.sourceRect = cell.frame;
  778. CCPeekPop *vc = [[UIStoryboard storyboardWithName:@"CCPeekPop" bundle:nil] instantiateViewControllerWithIdentifier:@"PeekPopImagePreview"];
  779. vc.delegate = self;
  780. vc.metadata = metadata;
  781. return vc;
  782. }
  783. }
  784. return nil;
  785. }
  786. - (void)previewingContext:(id<UIViewControllerPreviewing>)previewingContext commitViewController:(UIViewController *)viewControllerToCommit
  787. {
  788. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:previewingContext.sourceRect.origin];
  789. [self tableView:self.tableView didSelectRowAtIndexPath:indexPath];
  790. }
  791. #pragma mark -
  792. #pragma --------------------------------------------------------------------------------------------
  793. #pragma mark ==== External Sites ====
  794. #pragma --------------------------------------------------------------------------------------------
  795. - (void)getExternalSitesServerSuccess:(NSArray *)listOfExternalSites
  796. {
  797. [[NCManageDatabase sharedInstance] deleteExternalSites];
  798. for (OCExternalSites *tableExternalSites in listOfExternalSites)
  799. [[NCManageDatabase sharedInstance] addExternalSites:tableExternalSites];
  800. }
  801. - (void)getExternalSitesServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  802. {
  803. NSLog(@"[LOG] No External Sites found");
  804. }
  805. #pragma --------------------------------------------------------------------------------------------
  806. #pragma mark ==== Activity ====
  807. #pragma --------------------------------------------------------------------------------------------
  808. - (void)getActivityServerSuccess:(NSArray *)listOfActivity
  809. {
  810. [[NCManageDatabase sharedInstance] addActivityServer:listOfActivity];
  811. // Reload Activity Data Source
  812. [app.activeActivity reloadDatasource];
  813. }
  814. - (void)getActivityServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  815. {
  816. NSLog(@"[LOG] No Activity found");
  817. }
  818. #pragma --------------------------------------------------------------------------------------------
  819. #pragma mark ==== Notification ====
  820. #pragma --------------------------------------------------------------------------------------------
  821. - (void)getNotificationServerSuccess:(NSArray *)listOfNotifications
  822. {
  823. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  824. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  825. // Order by date
  826. NSArray *sortedListOfNotifications = [listOfNotifications sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
  827. OCNotifications *notification1 = obj1, *notification2 = obj2;
  828. return [notification2.date compare: notification1.date];
  829. }];
  830. // verify if listOfNotifications is changed
  831. NSString *old = @"", *new = @"";
  832. for (OCNotifications *notification in listOfNotifications)
  833. new = [new stringByAppendingString:@(notification.idNotification).stringValue];
  834. for (OCNotifications *notification in appDelegate.listOfNotifications)
  835. old = [old stringByAppendingString:@(notification.idNotification).stringValue];
  836. if (![new isEqualToString:old]) {
  837. appDelegate.listOfNotifications = [[NSMutableArray alloc] initWithArray:sortedListOfNotifications];
  838. // reload Notification view
  839. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"notificationReloadData" object:nil];
  840. }
  841. // Update NavigationBar
  842. if (!_isSelectedMode) {
  843. [self performSelectorOnMainThread:@selector(setUINavigationBarDefault) withObject:nil waitUntilDone:NO];
  844. }
  845. });
  846. }
  847. - (void)getNotificationServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  848. {
  849. // Update NavigationBar
  850. if (!_isSelectedMode)
  851. [self setUINavigationBarDefault];
  852. }
  853. - (void)viewNotification
  854. {
  855. if ([app.listOfNotifications count] > 0) {
  856. CCNotification *notificationVC = [[UIStoryboard storyboardWithName:@"CCNotification" bundle:nil] instantiateViewControllerWithIdentifier:@"CCNotification"];
  857. [notificationVC setModalPresentationStyle:UIModalPresentationFormSheet];
  858. [self presentViewController:notificationVC animated:YES completion:nil];
  859. }
  860. }
  861. #pragma --------------------------------------------------------------------------------------------
  862. #pragma mark ==== User Profile ====
  863. #pragma --------------------------------------------------------------------------------------------
  864. - (void)getUserProfileFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  865. {
  866. if (errorCode == 401)
  867. [self changePasswordAccount];
  868. }
  869. - (void)getUserProfileSuccess:(CCMetadataNet *)metadataNet userProfile:(OCUserProfile *)userProfile
  870. {
  871. [[NCManageDatabase sharedInstance] setAccountsUserProfile:userProfile];
  872. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  873. NSString *address = [NSString stringWithFormat:@"%@/index.php/avatar/%@/128", app.activeUrl, app.activeUser];
  874. UIImage *avatar = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]];
  875. if (avatar)
  876. [UIImagePNGRepresentation(avatar) writeToFile:[NSString stringWithFormat:@"%@/avatar.png", app.directoryUser] atomically:YES];
  877. else
  878. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/avatar.png", app.directoryUser] error:nil];
  879. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"changeUserProfile" object:nil];
  880. });
  881. }
  882. #pragma --------------------------------------------------------------------------------------------
  883. #pragma mark ==== Capabilities ====
  884. #pragma --------------------------------------------------------------------------------------------
  885. - (void)getCapabilitiesOfServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  886. {
  887. // Change Theming color
  888. [app settingThemingColorBrand];
  889. if (errorCode == 401)
  890. [self changePasswordAccount];
  891. }
  892. - (void)getCapabilitiesOfServerSuccess:(OCCapabilities *)capabilities
  893. {
  894. // Update capabilities db
  895. [[NCManageDatabase sharedInstance] addCapabilities:capabilities];
  896. // ------ THEMING -----------------------------------------------------------------------
  897. // Download Theming Background & Change Theming color
  898. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  899. if ([NCBrandOptions sharedInstance].use_themingBackground == YES) {
  900. UIImage *themingBackground = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[capabilities.themingBackground stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]];
  901. if (themingBackground)
  902. [UIImagePNGRepresentation(themingBackground) writeToFile:[NSString stringWithFormat:@"%@/themingBackground.png", app.directoryUser] atomically:YES];
  903. else
  904. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/themingBackground.png", app.directoryUser] error:nil];
  905. }
  906. dispatch_async(dispatch_get_main_queue(), ^{
  907. [app settingThemingColorBrand];
  908. });
  909. });
  910. // ------ SEARCH ------------------------------------------------------------------------
  911. // Search bar if change version
  912. if ([[NCManageDatabase sharedInstance] getServerVersion] != capabilities.versionMajor) {
  913. [self cancelSearchBar];
  914. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  915. if (capabilities.versionMajor >= 12) {
  916. if (_isRoot)
  917. self.searchController.searchBar.placeholder = NSLocalizedString(@"_search_all_folders_",nil);
  918. else
  919. self.searchController.searchBar.placeholder = NSLocalizedString(@"_search_sub_folder_",nil);
  920. self.searchController.searchBar.scopeButtonTitles = [NSArray arrayWithObjects:NSLocalizedString(@"_search_this_folder_",nil),self.searchController.searchBar.placeholder, nil];
  921. } else {
  922. self.searchController.searchBar.placeholder = NSLocalizedString(@"_search_this_folder_",nil);
  923. self.searchController.searchBar.scopeButtonTitles = nil;
  924. }
  925. _depth = @"0";
  926. });
  927. }
  928. // ------ GET SERVICE SERVER ------------------------------------------------------------
  929. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  930. // Read External Sites
  931. if (capabilities.isExternalSitesServerEnabled) {
  932. metadataNet.action = actionGetExternalSitesServer;
  933. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  934. }
  935. // Read Share
  936. if (capabilities.isFilesSharingAPIEnabled) {
  937. [app.sharesID removeAllObjects];
  938. metadataNet.action = actionReadShareServer;
  939. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  940. }
  941. // Read Notification
  942. metadataNet.action = actionGetNotificationServer;
  943. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  944. // Read User Profile
  945. metadataNet.action = actionGetUserProfile;
  946. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  947. // Read Activity
  948. metadataNet.action = actionGetActivityServer;
  949. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  950. }
  951. #pragma mark -
  952. #pragma --------------------------------------------------------------------------------------------
  953. #pragma mark ==== Request Server Information ====
  954. #pragma --------------------------------------------------------------------------------------------
  955. - (void)requestServerCapabilities
  956. {
  957. // test
  958. if (app.activeAccount.length == 0)
  959. return;
  960. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  961. metadataNet.action = actionGetCapabilities;
  962. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  963. }
  964. #pragma mark -
  965. #pragma --------------------------------------------------------------------------------------------
  966. #pragma mark ==== Download Thumbnail Delegate ====
  967. #pragma --------------------------------------------------------------------------------------------
  968. - (void)downloadThumbnailSuccess:(CCMetadataNet *)metadataNet
  969. {
  970. __block CCCellMain *cell;
  971. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadataNet.fileID];
  972. if (indexPath && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadataNet.fileID]]) {
  973. cell = [self.tableView cellForRowAtIndexPath:indexPath];
  974. cell.fileImageView.image = [app.icoImagesCache objectForKey:metadataNet.fileID];
  975. if (cell.fileImageView.image == nil) {
  976. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  977. UIImage *image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadataNet.fileID]];
  978. [app.icoImagesCache setObject:image forKey:metadataNet.fileID];
  979. });
  980. }
  981. }
  982. }
  983. #pragma --------------------------------------------------------------------------------------------
  984. #pragma mark ==== Download ====
  985. #pragma --------------------------------------------------------------------------------------------
  986. - (void)downloadFileFailure:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector message:(NSString *)message errorCode:(NSInteger)errorCode
  987. {
  988. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  989. // File do not exists on server, remove in local
  990. if (errorCode == kOCErrorServerPathNotFound || errorCode == kCFURLErrorBadServerResponse) {
  991. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, fileID] error:nil];
  992. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, fileID] error:nil];
  993. if (metadata.directory && serverUrl) {
  994. NSString *dirForDelete = [CCUtility stringAppendServerUrl:serverUrl addFileName:metadata.fileNameData];
  995. [[NCManageDatabase sharedInstance] deleteDirectoryAndSubDirectoryWithServerUrl:dirForDelete];
  996. }
  997. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  998. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  999. }
  1000. if ([selector isEqualToString:selectorLoadViewImage]) {
  1001. dispatch_async(dispatch_get_main_queue(), ^{
  1002. // Updating Detail
  1003. if (app.activeDetail)
  1004. [app.activeDetail downloadPhotoBrowserFailure:errorCode];
  1005. // Updating Photos
  1006. if (app.activePhotos)
  1007. [app.activePhotos downloadFileFailure:errorCode];
  1008. });
  1009. } else {
  1010. if (errorCode != kCFURLErrorCancelled)
  1011. [app messageNotification:@"_download_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1012. }
  1013. [self reloadDatasource:serverUrl fileID:fileID selector:selector];
  1014. }
  1015. - (void)downloadFileSuccess:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector selectorPost:(NSString *)selectorPost
  1016. {
  1017. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  1018. if (metadata == nil) return;
  1019. // Download
  1020. if ([selector isEqualToString:selectorDownloadFile]) {
  1021. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1022. }
  1023. // Synchronized
  1024. if ([selector isEqualToString:selectorDownloadSynchronize]) {
  1025. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1026. }
  1027. // add Favorite
  1028. if ([selector isEqualToString:selectorAddFavorite]) {
  1029. [[CCActions sharedInstance] settingFavorite:metadata favorite:YES delegate:self];
  1030. }
  1031. // encrypted file
  1032. if ([selector isEqualToString:selectorEncryptFile]) {
  1033. [self encryptedFile:metadata];
  1034. }
  1035. // decrypted file
  1036. if ([selector isEqualToString:selectorDecryptFile]) {
  1037. [self decryptedFile:metadata];
  1038. }
  1039. // open View File
  1040. if ([selector isEqualToString:selectorLoadFileView] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  1041. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1042. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_compress]) {
  1043. [self performSelector:@selector(unZipFile:) withObject:metadata.fileID];
  1044. } else if ([metadata.typeFile isEqualToString: k_metadataTypeFile_unknown]) {
  1045. selector = selectorOpenIn;
  1046. } else {
  1047. _metadata = metadata;
  1048. if ([self shouldPerformSegue])
  1049. [self performSegueWithIdentifier:@"segueDetail" sender:self];
  1050. }
  1051. }
  1052. // addLocal
  1053. if ([selector isEqualToString:selectorAddLocal]) {
  1054. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] toPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryLocal], metadata.fileNamePrint]];
  1055. UIImage *image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]];
  1056. [CCGraphics saveIcoWithEtag:metadata.fileNamePrint image:image writeToFile:nil copy:YES move:NO fromPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID] toPath:[NSString stringWithFormat:@"%@/.%@.ico", [CCUtility getDirectoryLocal], metadata.fileNamePrint]];
  1057. [app messageNotification:@"_add_local_" description:@"_file_saved_local_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess errorCode:0];
  1058. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1059. }
  1060. // Open with...
  1061. if ([selector isEqualToString:selectorOpenIn] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  1062. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1063. [[NSFileManager defaultManager] removeItemAtPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint] error:nil];
  1064. [[NSFileManager defaultManager] linkItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] toPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint] error:nil];
  1065. NSURL *url = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint]];
  1066. _docController = [UIDocumentInteractionController interactionControllerWithURL:url];
  1067. _docController.delegate = self;
  1068. [_docController presentOptionsMenuFromRect:self.view.frame inView:self.view animated:YES];
  1069. }
  1070. // Save to Photo Album
  1071. if ([selector isEqualToString:selectorSave] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  1072. NSString *file = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID];
  1073. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image]) {
  1074. // evitiamo il rimando photo
  1075. [[NCManageDatabase sharedInstance] setAccountAutoUploadDateAssetType:PHAssetMediaTypeImage assetDate:[NSDate date]];
  1076. UIImage *image = [UIImage imageWithContentsOfFile:file];
  1077. if (image)
  1078. UIImageWriteToSavedPhotosAlbum(image, self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  1079. else
  1080. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1081. }
  1082. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_video]) {
  1083. // we avoid the cross-reference video
  1084. [[NCManageDatabase sharedInstance] setAccountAutoUploadDateAssetType:PHAssetMediaTypeVideo assetDate:[NSDate date]];
  1085. [[NSFileManager defaultManager] linkItemAtPath:file toPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint] error:nil];
  1086. if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum([NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint])) {
  1087. UISaveVideoAtPathToSavedPhotosAlbum([NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint], self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  1088. } else {
  1089. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1090. }
  1091. }
  1092. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1093. }
  1094. // Copy File
  1095. if ([selector isEqualToString:selectorLoadCopy]) {
  1096. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1097. [self copyFileToPasteboard:metadata];
  1098. }
  1099. // download and view a template
  1100. if ([selector isEqualToString:selectorLoadModelView]) {
  1101. metadata = [CCUtility insertInformationPlist:metadata directoryUser:app.directoryUser];
  1102. metadata = [[NCManageDatabase sharedInstance] updateMetadata:metadata activeUrl:app.activeUrl];
  1103. // se è un template aggiorniamo anche nel FileSystem
  1104. if ([metadata.type isEqualToString: k_metadataType_template]) {
  1105. [[NCManageDatabase sharedInstance] setLocalFileWithFileID:metadata.fileID date:metadata.date exifDate:nil exifLatitude:nil exifLongitude:nil fileName:nil fileNamePrint:metadata.fileNamePrint];
  1106. }
  1107. [self openModel:metadata.model isNew:false];
  1108. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1109. }
  1110. //download file plist
  1111. if ([selector isEqualToString:selectorLoadPlist]) {
  1112. metadata = [CCUtility insertInformationPlist:metadata directoryUser:app.directoryUser];
  1113. metadata = [[NCManageDatabase sharedInstance] updateMetadata:metadata activeUrl:app.activeUrl];
  1114. // se è un template aggiorniamo anche nel FileSystem
  1115. if ([metadata.type isEqualToString: k_metadataType_template]) {
  1116. [[NCManageDatabase sharedInstance] setLocalFileWithFileID:metadata.fileID date:metadata.date exifDate:nil exifLatitude:nil exifLongitude:nil fileName:nil fileNamePrint:metadata.fileNamePrint];
  1117. }
  1118. long countSelectorLoadPlist = 0;
  1119. for (NSOperation *operation in [app.netQueue operations]) {
  1120. if ([((OCnetworking *)operation).metadataNet.selector isEqualToString:selectorLoadPlist])
  1121. countSelectorLoadPlist++;
  1122. }
  1123. if ((countSelectorLoadPlist == 0 || countSelectorLoadPlist % k_maxConcurrentOperation == 0) && [metadata.directoryID isEqualToString:[[NCManageDatabase sharedInstance] getDirectoryID:_serverUrl]]) {
  1124. dispatch_async(dispatch_get_main_queue(), ^{
  1125. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1126. });
  1127. }
  1128. }
  1129. //selectorLoadViewImage
  1130. if ([selector isEqualToString:selectorLoadViewImage]) {
  1131. dispatch_async(dispatch_get_main_queue(), ^{
  1132. // Detail
  1133. if (app.activeDetail)
  1134. [app.activeDetail downloadPhotoBrowserSuccess:metadata selector:selector];
  1135. // Photos
  1136. if (app.activePhotos)
  1137. [app.activePhotos downloadFileSuccess:metadata];
  1138. });
  1139. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1140. }
  1141. // if exists postselector call self with selectorPost
  1142. if ([selectorPost length] > 0)
  1143. [self downloadFileSuccess:fileID serverUrl:serverUrl selector:selectorPost selectorPost:nil];
  1144. }
  1145. - (void)downloadSelectedFiles
  1146. {
  1147. NSLog(@"[LOG] Start download selected files ...");
  1148. [_hud visibleHudTitle:NSLocalizedString(@"_downloading_progress_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1149. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1150. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1151. for (tableMetadata *metadata in selectedMetadatas) {
  1152. if (metadata.directory == NO && [metadata.type isEqualToString: k_metadataType_file]) {
  1153. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1154. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorDownloadFile selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  1155. }
  1156. }
  1157. [_hud hideHud];
  1158. });
  1159. [self tableViewSelect:NO];
  1160. }
  1161. - (void)downloadPlist:(NSString *)directoryID serverUrl:(NSString *)serverUrl
  1162. {
  1163. NSArray *metadatas = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND session = ''", app.activeAccount, directoryID] sorted:nil ascending:NO];
  1164. for (tableMetadata *metadata in metadatas) {
  1165. if ([CCUtility isCryptoPlistString:metadata.fileName] && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileName]] == NO && [metadata.session length] == 0) {
  1166. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1167. metadataNet.action = actionDownloadFile;
  1168. metadataNet.downloadData = NO;
  1169. metadataNet.downloadPlist = YES;
  1170. metadataNet.fileID = metadata.fileID;
  1171. metadataNet.selector = selectorLoadPlist;
  1172. metadataNet.serverUrl = serverUrl;
  1173. metadataNet.session = k_download_session_foreground;
  1174. metadataNet.taskStatus = k_taskStatusResume;
  1175. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1176. }
  1177. }
  1178. }
  1179. #pragma --------------------------------------------------------------------------------------------
  1180. #pragma mark ===== Upload new Photos/Videos =====
  1181. #pragma --------------------------------------------------------------------------------------------
  1182. - (void)uploadFileFailure:(CCMetadataNet *)metadataNet fileID:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector message:(NSString *)message errorCode:(NSInteger)errorCode
  1183. {
  1184. // Automatic upload All
  1185. if([selector isEqualToString:selectorUploadAutomaticAll])
  1186. [app performSelectorOnMainThread:@selector(loadAutomaticUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUpload] waitUntilDone:NO];
  1187. // Read File test do not exists
  1188. if (errorCode == k_CCErrorFileUploadNotFound && fileID) {
  1189. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  1190. // reUpload
  1191. if (metadata)
  1192. [[CCNetworking sharedNetworking] uploadFileMetadata:metadata taskStatus:k_taskStatusResume];
  1193. }
  1194. // Print error
  1195. else if (errorCode != kCFURLErrorCancelled && errorCode != 403) {
  1196. [app messageNotification:@"_upload_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1197. }
  1198. [self reloadDatasource:serverUrl fileID:nil selector:selector];
  1199. }
  1200. - (void)uploadFileSuccess:(CCMetadataNet *)metadataNet fileID:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector selectorPost:(NSString *)selectorPost
  1201. {
  1202. // Automatic upload All
  1203. if([selector isEqualToString:selectorUploadAutomaticAll])
  1204. [app performSelectorOnMainThread:@selector(loadAutomaticUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUpload] waitUntilDone:NO];
  1205. if ([selectorPost isEqualToString:selectorReadFolderForced] ) {
  1206. [self readFolderWithForced:YES serverUrl:serverUrl];
  1207. } else {
  1208. [self reloadDatasource:serverUrl fileID:nil selector:selector];
  1209. }
  1210. }
  1211. //
  1212. // This procedure with performSelectorOnMainThread it's necessary after (Bridge) for use the function "Sync" in OCNetworking
  1213. //
  1214. - (void)uploadFileAsset:(NSMutableArray *)assets serverUrl:(NSString *)serverUrl cryptated:(BOOL)cryptated useSubFolder:(BOOL)useSubFolder session:(NSString *)session
  1215. {
  1216. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void){
  1217. [self performSelectorOnMainThread:@selector(uploadFileAssetBridge:) withObject:@[assets, serverUrl, [NSNumber numberWithBool:cryptated], [NSNumber numberWithBool:useSubFolder], session] waitUntilDone:NO];
  1218. });
  1219. }
  1220. - (void)uploadFileAssetBridge:(NSArray *)arguments
  1221. {
  1222. NSArray *assets = [arguments objectAtIndex:0];
  1223. NSString *serverUrl = [arguments objectAtIndex:1];
  1224. BOOL cryptated = [[arguments objectAtIndex:2] boolValue];
  1225. BOOL useSubFolder = [[arguments objectAtIndex:3] boolValue];
  1226. NSString *session = [arguments objectAtIndex:4];
  1227. NSString *autoUploadPath = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:app.activeUrl];
  1228. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl];
  1229. // Create the folder for Photos & if request the subfolders
  1230. if (![app createFolderSubFolderAutomaticUploadFolderPhotos:autoUploadPath useSubFolder:useSubFolder assets:assets selector:selectorUploadFile])
  1231. return;
  1232. NSLog(@"[LOG] Asset N. %lu", (unsigned long)[assets count]);
  1233. for (PHAsset *asset in assets) {
  1234. NSString *fileName = [CCUtility createFileNameFromAsset:asset key: k_keyFileNameMask];
  1235. NSDate *assetDate = asset.creationDate;
  1236. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  1237. // Create serverUrl if use sub folder
  1238. if (useSubFolder) {
  1239. [formatter setDateFormat:@"yyyy"];
  1240. NSString *yearString = [formatter stringFromDate:assetDate];
  1241. [formatter setDateFormat:@"MM"];
  1242. NSString *monthString = [formatter stringFromDate:assetDate];
  1243. serverUrl = [NSString stringWithFormat:@"%@/%@/%@", autoUploadPath, yearString, monthString];
  1244. }
  1245. // Check if is in upload
  1246. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND fileName = %@ AND session != ''", app.activeAccount, directoryID, fileName];
  1247. NSArray *isRecordInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:predicate sorted:nil ascending:NO];
  1248. if ([isRecordInSessions count] > 0) {
  1249. // next upload
  1250. continue;
  1251. } else {
  1252. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1253. if (cryptated) {
  1254. metadataNet.action = actionUploadAsset;
  1255. metadataNet.assetLocalIdentifier = asset.localIdentifier;
  1256. metadataNet.cryptated = cryptated;
  1257. metadataNet.fileName = fileName;
  1258. metadataNet.priority = NSOperationQueuePriorityNormal;
  1259. metadataNet.session = session;
  1260. metadataNet.selector = selectorUploadFile;
  1261. metadataNet.selectorPost = nil;
  1262. metadataNet.serverUrl = serverUrl;
  1263. metadataNet.taskStatus = k_taskStatusResume;
  1264. } else {
  1265. metadataNet.action = actionReadFile;
  1266. metadataNet.assetLocalIdentifier = asset.localIdentifier;
  1267. metadataNet.cryptated = cryptated;
  1268. metadataNet.fileName = fileName;
  1269. metadataNet.priority = NSOperationQueuePriorityNormal;
  1270. metadataNet.session = session;
  1271. metadataNet.selector = selectorReadFileUploadFile;
  1272. metadataNet.serverUrl = serverUrl;
  1273. }
  1274. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1275. }
  1276. }
  1277. }
  1278. #pragma --------------------------------------------------------------------------------------------
  1279. #pragma mark ==== Read File ====
  1280. #pragma --------------------------------------------------------------------------------------------
  1281. - (void)readFileFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1282. {
  1283. // UploadFile
  1284. if ([metadataNet.selector isEqualToString:selectorReadFileUploadFile]) {
  1285. // File not exists
  1286. if (errorCode == 404) {
  1287. metadataNet.action = actionUploadAsset;
  1288. metadataNet.errorCode = 0;
  1289. metadataNet.selector = selectorUploadFile;
  1290. metadataNet.selectorPost = nil;
  1291. metadataNet.taskStatus = k_taskStatusResume;
  1292. if ([metadataNet.session containsString:@"wwan"])
  1293. [app addNetworkingOperationQueue:app.netQueueUploadWWan delegate:self metadataNet:metadataNet];
  1294. else
  1295. [app addNetworkingOperationQueue:app.netQueueUpload delegate:self metadataNet:metadataNet];
  1296. } else {
  1297. // error ho many retry befor notification and go to on next asses
  1298. if (metadataNet.errorRetry < 3) {
  1299. // Retry read file
  1300. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1301. } else {
  1302. // STOP check file, view message error
  1303. [app messageNotification:@"_upload_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1304. }
  1305. }
  1306. }
  1307. }
  1308. - (void)readFileSuccess:(CCMetadataNet *)metadataNet metadata:(tableMetadata *)metadata
  1309. {
  1310. // UploadFile
  1311. if ([metadataNet.selector isEqualToString:selectorReadFileUploadFile]) {
  1312. metadataNet.action = actionUploadAsset;
  1313. metadataNet.errorCode = 403; // File exists 403 Forbidden
  1314. metadataNet.selector = selectorUploadFile;
  1315. metadataNet.selectorPost = nil;
  1316. metadataNet.taskStatus = k_taskStatusResume;
  1317. if ([metadataNet.session containsString:@"wwan"])
  1318. [app addNetworkingOperationQueue:app.netQueueUploadWWan delegate:self metadataNet:metadataNet];
  1319. else
  1320. [app addNetworkingOperationQueue:app.netQueueUpload delegate:self metadataNet:metadataNet];
  1321. }
  1322. }
  1323. #pragma --------------------------------------------------------------------------------------------
  1324. #pragma mark ==== Read Folder ====
  1325. #pragma --------------------------------------------------------------------------------------------
  1326. - (void)readFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1327. {
  1328. // verify active user
  1329. tableAccount *record = [[NCManageDatabase sharedInstance] getAccountActive];
  1330. [_hud hideHud];
  1331. [_refreshControl endRefreshing];
  1332. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  1333. if (message && [record.account isEqualToString:metadataNet.account])
  1334. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1335. [self reloadDatasource:metadataNet.serverUrl fileID:nil selector:metadataNet.selector];
  1336. if (errorCode == 401)
  1337. [self changePasswordAccount];
  1338. }
  1339. - (void)readFolderSuccess:(CCMetadataNet *)metadataNet permissions:(NSString *)permissions etag:(NSString *)etag metadatas:(NSArray *)metadatas
  1340. {
  1341. // verify active user
  1342. tableAccount *record = [[NCManageDatabase sharedInstance] getAccountActive];
  1343. if (![record.account isEqualToString:metadataNet.account])
  1344. return;
  1345. // save father e update permission
  1346. if(!_isSearchMode)
  1347. _fatherPermission = permissions;
  1348. NSArray *recordsInSessions;
  1349. if (_isSearchMode) {
  1350. recordsInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND session != ''", metadataNet.account] sorted:nil ascending:NO];
  1351. } else {
  1352. [[NCManageDatabase sharedInstance] setDirectoryWithServerUrl:metadataNet.serverUrl serverUrlTo:nil etag:etag];
  1353. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND session = ''", metadataNet.account, metadataNet.directoryID]];
  1354. recordsInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND session != ''", metadataNet.account, metadataNet.directoryID] sorted:nil ascending:NO];
  1355. [[NCManageDatabase sharedInstance] setDateReadDirectoryWithDirectoryID:metadataNet.directoryID];
  1356. }
  1357. for (tableMetadata *metadata in metadatas) {
  1358. // type of file
  1359. NSInteger typeFilename = [CCUtility getTypeFileName:metadata.fileName];
  1360. // if crypto do not insert
  1361. if (typeFilename == k_metadataTypeFilenameCrypto) continue;
  1362. // verify if the record encrypted has plist + crypto
  1363. if (typeFilename == k_metadataTypeFilenamePlist && metadata.directory == NO) {
  1364. BOOL isCryptoComplete = NO;
  1365. NSString *fileNameCrypto = [CCUtility trasformedFileNamePlistInCrypto:metadata.fileName];
  1366. for (tableMetadata *completeMetadata in metadatas) {
  1367. if (completeMetadata.cryptated == NO) continue;
  1368. else if ([completeMetadata.fileName isEqualToString:fileNameCrypto]) {
  1369. isCryptoComplete = YES;
  1370. break;
  1371. }
  1372. }
  1373. if (isCryptoComplete == NO) continue;
  1374. }
  1375. // verify if the record is in download/upload progress
  1376. if (metadata.directory == NO && [recordsInSessions count] > 0) {
  1377. tableMetadata *metadataTransfer = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND fileName = %@", app.activeAccount, metadataNet.directoryID, metadata.fileName]];
  1378. // is in Download or Upload
  1379. if ([metadataTransfer.session containsString:@"upload"] || [metadataTransfer.session containsString:@"download"]) {
  1380. continue;
  1381. }
  1382. }
  1383. // end test, insert in Database
  1384. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata activeUrl:app.activeUrl];
  1385. }
  1386. // read plist
  1387. if (!_isSearchMode)
  1388. [self downloadPlist:metadataNet.directoryID serverUrl:metadataNet.serverUrl];
  1389. // File is changed ??
  1390. if (!_isSearchMode)
  1391. [[CCSynchronize sharedSynchronize] verifyChangeMedatas:metadatas serverUrl:metadataNet.serverUrl account:app.activeAccount withDownload:NO];
  1392. // Search Mode
  1393. if (_isSearchMode)
  1394. [self reloadDatasource:metadataNet.serverUrl fileID:nil selector:metadataNet.selector];
  1395. // this is the same directory
  1396. if ([metadataNet.serverUrl isEqualToString:_serverUrl] && !_isSearchMode) {
  1397. // reload
  1398. [self reloadDatasource:metadataNet.serverUrl fileID:nil selector:metadataNet.selector];
  1399. // stoprefresh
  1400. [_refreshControl endRefreshing];
  1401. // Enable change user
  1402. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  1403. [_hud hideHud];
  1404. }
  1405. }
  1406. - (void)readFolderWithForced:(BOOL)forced serverUrl:(NSString *)serverUrl
  1407. {
  1408. // init control
  1409. if (!serverUrl || !app.activeAccount)
  1410. return;
  1411. // Search Mode
  1412. if (_isSearchMode) {
  1413. if (forced) {
  1414. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:serverUrl directoryID:nil];
  1415. _searchFileName = @""; // forced reload searchg
  1416. }
  1417. [self updateSearchResultsForSearchController:self.searchController];
  1418. return;
  1419. }
  1420. BOOL isDirectoryOutOfDate = true;
  1421. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"serverUrl = %@", serverUrl]];
  1422. if (directory.dateReadDirectory) {
  1423. // Is Directory Out Of Date ?
  1424. NSDateComponents *dateComponents = [NSDateComponents new];
  1425. [dateComponents setWeekday:k_dayForceReadFolder];
  1426. NSCalendar *calendar = [NSCalendar currentCalendar];
  1427. NSDate *datePlus = [calendar dateByAddingComponents:dateComponents toDate:directory.dateReadDirectory options:0];
  1428. NSDate *now = [NSDate date];
  1429. // usa la Cache se richiesto e se la data è entro X giorni dall'ultima volta che l'hai letta.
  1430. if ([now compare:datePlus] == NSOrderedDescending)
  1431. isDirectoryOutOfDate = true;
  1432. else
  1433. isDirectoryOutOfDate = false;
  1434. }
  1435. if (isDirectoryOutOfDate || forced) {
  1436. if (_refreshControl.isRefreshing == NO)
  1437. [_hud visibleIndeterminateHud];
  1438. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1439. metadataNet.action = actionReadFolder;
  1440. metadataNet.date = [NSDate date];
  1441. metadataNet.directoryID = directory.directoryID;
  1442. metadataNet.priority = NSOperationQueuePriorityHigh;
  1443. metadataNet.selector = selectorReadFolder;
  1444. metadataNet.serverUrl = serverUrl;
  1445. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1446. }
  1447. }
  1448. #pragma mark -
  1449. #pragma --------------------------------------------------------------------------------------------
  1450. #pragma mark ===== Search =====
  1451. #pragma --------------------------------------------------------------------------------------------
  1452. -(void)updateSearchResultsForSearchController:(UISearchController *)searchController
  1453. {
  1454. _isSearchMode = YES;
  1455. [self deleteRefreshControl];
  1456. NSString *fileName = [CCUtility removeForbiddenCharactersServer:searchController.searchBar.text];
  1457. if (fileName.length >= k_minCharsSearch && [fileName isEqualToString:_searchFileName] == NO) {
  1458. _searchFileName = fileName;
  1459. if ([[NCManageDatabase sharedInstance] getServerVersion] >= 12 && ![_depth isEqualToString:@"0"]) {
  1460. [[CCActions sharedInstance] search:_serverUrl fileName:_searchFileName depth:_depth delegate:self];
  1461. _noFilesSearchTitle = @"";
  1462. _noFilesSearchDescription = NSLocalizedString(@"_search_in_progress_", nil);
  1463. [self.tableView reloadEmptyDataSet];
  1464. } else {
  1465. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:_serverUrl];
  1466. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"directoryID = %@ AND account = %@ AND fileNamePrint CONTAINS[cd] %@", directoryID, app.activeAccount, fileName];
  1467. NSArray *records = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:predicate sorted:nil ascending:NO];
  1468. [_searchResultMetadatas removeAllObjects];
  1469. for (tableMetadata *record in records)
  1470. [_searchResultMetadatas addObject:record];
  1471. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1472. metadataNet.account = app.activeAccount;
  1473. metadataNet.action = actionUploadTemplate;
  1474. metadataNet.directoryID = directoryID;
  1475. metadataNet.selector = selectorSearch;
  1476. metadataNet.serverUrl = _serverUrl;
  1477. [self readFolderSuccess:metadataNet permissions:@"" etag:@"" metadatas:_searchResultMetadatas];
  1478. }
  1479. }
  1480. if (_searchResultMetadatas.count == 0 && fileName.length == 0) {
  1481. [self reloadDatasource];
  1482. }
  1483. }
  1484. - (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
  1485. {
  1486. [self cancelSearchBar];
  1487. [self readFolderWithForced:NO serverUrl:_serverUrl];
  1488. }
  1489. - (void)searchFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1490. {
  1491. _searchFileName = @"";
  1492. if (message)
  1493. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1494. }
  1495. - (void)searchSuccess:(CCMetadataNet *)metadataNet metadatas:(NSArray *)metadatas
  1496. {
  1497. _searchResultMetadatas = [[NSMutableArray alloc] initWithArray:metadatas];
  1498. [self readFolderSuccess:metadataNet permissions:nil etag:nil metadatas:metadatas];
  1499. }
  1500. - (void)cancelSearchBar
  1501. {
  1502. if (self.searchController.active) {
  1503. [self.searchController setActive:NO];
  1504. [self createRefreshControl];
  1505. _isSearchMode = NO;
  1506. _searchFileName = @"";
  1507. _dateReadDataSource = nil;
  1508. _searchResultMetadatas = [NSMutableArray new];
  1509. [self reloadDatasource];
  1510. }
  1511. }
  1512. - (void)searchBar:(UISearchBar *)searchBar selectedScopeButtonIndexDidChange:(NSInteger)selectedScope
  1513. {
  1514. NSString *title = [self.searchController.searchBar.scopeButtonTitles objectAtIndex:selectedScope];
  1515. self.searchController.searchBar.placeholder = title;
  1516. if ([title isEqualToString:NSLocalizedString(@"_search_this_folder_",nil)])
  1517. _depth = @"0";
  1518. if ([title isEqualToString:NSLocalizedString(@"_search_sub_folder_",nil)])
  1519. _depth = @"1";
  1520. if ([title isEqualToString:NSLocalizedString(@"_search_all_folders_",nil)])
  1521. _depth = @"infinity";
  1522. _searchFileName = @"";
  1523. [self updateSearchResultsForSearchController:self.searchController];
  1524. }
  1525. #pragma mark -
  1526. #pragma --------------------------------------------------------------------------------------------
  1527. #pragma mark ===== Delete File or Folder =====
  1528. #pragma --------------------------------------------------------------------------------------------
  1529. - (void)deleteFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1530. {
  1531. [self deleteFileOrFolderSuccess:metadataNet];
  1532. }
  1533. - (void)deleteFileOrFolderSuccess:(CCMetadataNet *)metadataNet
  1534. {
  1535. [_queueSelector removeObject:metadataNet.selector];
  1536. if ([_queueSelector count] == 0) {
  1537. [_hud hideHud];
  1538. if (_isSearchMode)
  1539. [self readFolderWithForced:YES serverUrl:metadataNet.serverUrl];
  1540. else
  1541. [self reloadDatasource:metadataNet.serverUrl fileID:metadataNet.fileID selector:metadataNet.selector];
  1542. // next
  1543. if ([_selectedMetadatas count] > 0) {
  1544. [_selectedMetadatas removeObjectAtIndex:0];
  1545. if ([_selectedMetadatas count] > 0)
  1546. [self deleteFileOrFolder:[_selectedMetadatas objectAtIndex:0] numFile:[_selectedMetadatas count] ofFile:_numSelectedMetadatas];
  1547. }
  1548. }
  1549. }
  1550. - (void)deleteFileOrFolder:(tableMetadata *)metadata numFile:(NSInteger)numFile ofFile:(NSInteger)ofFile
  1551. {
  1552. if (metadata.cryptated) {
  1553. [_queueSelector addObject:selectorDeleteCrypto];
  1554. [_queueSelector addObject:selectorDeletePlist];
  1555. } else {
  1556. [_queueSelector addObject:selectorDelete];
  1557. }
  1558. [[CCActions sharedInstance] deleteFileOrFolder:metadata delegate:self];
  1559. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_delete_file_n_", nil), ofFile - numFile + 1, ofFile] mode:MBProgressHUDModeIndeterminate color:nil];
  1560. }
  1561. - (void)deleteSelectionFile
  1562. {
  1563. [_selectedMetadatas removeAllObjects];
  1564. [_queueSelector removeAllObjects];
  1565. _selectedMetadatas = [[NSMutableArray alloc] initWithArray: [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]]];
  1566. _numSelectedMetadatas = [_selectedMetadatas count];
  1567. if ([_selectedMetadatas count] > 0)
  1568. [self deleteFileOrFolder:[_selectedMetadatas objectAtIndex:0] numFile:[_selectedMetadatas count] ofFile:_numSelectedMetadatas];
  1569. [self tableViewSelect:NO];
  1570. }
  1571. - (void)deleteFile
  1572. {
  1573. [_selectedMetadatas removeAllObjects];
  1574. [_queueSelector removeAllObjects];
  1575. _numSelectedMetadatas = 1;
  1576. [_selectedMetadatas addObject:_metadata];
  1577. if ([_selectedMetadatas count] > 0)
  1578. [self deleteFileOrFolder:[_selectedMetadatas objectAtIndex:0] numFile:[_selectedMetadatas count] ofFile:_numSelectedMetadatas];
  1579. [self tableViewSelect:NO];
  1580. }
  1581. #pragma --------------------------------------------------------------------------------------------
  1582. #pragma mark ===== Rename / Move =====
  1583. #pragma --------------------------------------------------------------------------------------------
  1584. - (void)renameSuccess:(CCMetadataNet *)metadataNet
  1585. {
  1586. [self readFolderWithForced:YES serverUrl:metadataNet.serverUrl];
  1587. }
  1588. - (void)renameFile:(tableMetadata *)metadata fileName:(NSString *)fileName
  1589. {
  1590. [[CCActions sharedInstance] renameFileOrFolder:metadata fileName:fileName delegate:self];
  1591. }
  1592. - (void)renameNote:(tableMetadata *)metadata fileName:(NSString *)fileName
  1593. {
  1594. CCTemplates *templates = [[CCTemplates alloc] init];
  1595. NSMutableDictionary *field = [[CCCrypto sharedManager] getDictionaryEncrypted:metadata.fileName uuid:metadata.uuid isLocal:NO directoryUser:app.directoryUser];
  1596. NSString *fileNameModel = [templates salvaNote:[field objectForKey:@"note"] titolo:fileName fileName:metadata.fileName uuid:metadata.uuid];
  1597. if (fileNameModel) {
  1598. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1599. metadataNet.action = actionUploadTemplate;
  1600. metadataNet.fileName = [CCUtility trasformedFileNamePlistInCrypto:fileNameModel];
  1601. metadataNet.fileNamePrint = fileName;
  1602. metadataNet.etag = metadata.etag;
  1603. metadataNet.serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1604. metadataNet.session = k_upload_session_foreground;
  1605. metadataNet.taskStatus = k_taskStatusResume;
  1606. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1607. }
  1608. }
  1609. - (void)renameMoveFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1610. {
  1611. if ([metadataNet.selector isEqualToString:selectorMove]) {
  1612. [_hud hideHud];
  1613. if (message)
  1614. [app messageNotification:@"_move_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1615. [_selectedMetadatas removeAllObjects];
  1616. [_queueSelector removeAllObjects];
  1617. }
  1618. }
  1619. - (void)moveSuccess:(CCMetadataNet *)metadataNet
  1620. {
  1621. [_queueSelector removeObject:metadataNet.selector];
  1622. if ([_queueSelector count] == 0) {
  1623. [_hud hideHud];
  1624. NSString *fileName = [CCUtility trasformedFileNameCryptoInPlist:metadataNet.fileName];
  1625. NSString *directoryID = metadataNet.directoryID;
  1626. NSString *directoryIDTo = metadataNet.directoryIDTo;
  1627. NSString *serverUrlTo = [[NCManageDatabase sharedInstance] getServerUrl:directoryIDTo];
  1628. // FILE -> Metadata
  1629. if (metadataNet.directory == NO) {
  1630. // move metadata
  1631. //[CCCoreData moveMetadata:fileName directoryID:directoryID directoryIDTo:directoryIDTo activeAccount:app.activeAccount];
  1632. [[NCManageDatabase sharedInstance] moveMetadataWithFileName:fileName directoryID:directoryID directoryIDTo:directoryIDTo];
  1633. }
  1634. // DIRECTORY -> Directory - CCMetadata
  1635. if (metadataNet.directory == YES) {
  1636. // delete all dir / subdir
  1637. [[NCManageDatabase sharedInstance] deleteDirectoryAndSubDirectoryWithServerUrl:[CCUtility stringAppendServerUrl:metadataNet.serverUrl addFileName:fileName]];
  1638. // move metadata
  1639. //[CCCoreData moveMetadata:fileName directoryID:directoryID directoryIDTo:directoryIDTo activeAccount:app.activeAccount];
  1640. [[NCManageDatabase sharedInstance] moveMetadataWithFileName:fileName directoryID:directoryID directoryIDTo:directoryIDTo];
  1641. // Add new directory
  1642. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", serverUrlTo, fileName];
  1643. (void)[[NCManageDatabase sharedInstance] addDirectoryWithServerUrl:newDirectory permissions:@""];
  1644. }
  1645. // reload Datasource
  1646. if ([metadataNet.selectorPost isEqualToString:selectorReadFolderForced] || _isSearchMode)
  1647. [self readFolderWithForced:YES serverUrl:metadataNet.serverUrl];
  1648. else
  1649. [self reloadDatasource];
  1650. // Next file
  1651. [_selectedMetadatas removeObjectAtIndex:0];
  1652. [self performSelectorOnMainThread:@selector(moveFileOrFolder:) withObject:metadataNet.serverUrlTo waitUntilDone:NO];
  1653. }
  1654. }
  1655. - (void)moveFileOrFolder:(NSString *)serverUrlTo
  1656. {
  1657. if ([_selectedMetadatas count] > 0) {
  1658. tableMetadata *metadata = [_selectedMetadatas objectAtIndex:0];
  1659. // Plain
  1660. if (metadata.cryptated == NO) {
  1661. OCnetworking *ocNetworking = [[OCnetworking alloc] initWithDelegate:nil metadataNet:nil withUser:app.activeUser withPassword:app.activePassword withUrl:app.activeUrl isCryptoCloudMode:NO];
  1662. NSError *error = [ocNetworking readFileSync:[NSString stringWithFormat:@"%@/%@", serverUrlTo, metadata.fileName]];
  1663. if(!error) {
  1664. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1665. UIAlertController * alert= [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_file_already_exists_", nil) preferredStyle:UIAlertControllerStyleAlert];
  1666. UIAlertAction* ok = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
  1667. }];
  1668. [alert addAction:ok];
  1669. [self presentViewController:alert animated:YES completion:nil];
  1670. });
  1671. return;
  1672. }
  1673. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1674. metadataNet.action = actionMoveFileOrFolder;
  1675. metadataNet.directory = metadata.directory;
  1676. metadataNet.fileID = metadata.fileID;
  1677. metadataNet.directoryID = metadata.directoryID;
  1678. metadataNet.directoryIDTo = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrlTo];
  1679. metadataNet.fileName = metadata.fileName;
  1680. metadataNet.fileNamePrint = metadataNet.fileNamePrint;
  1681. metadataNet.fileNameTo = metadata.fileName;
  1682. metadataNet.etag = metadata.etag;
  1683. metadataNet.selector = selectorMove;
  1684. metadataNet.serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1685. metadataNet.serverUrlTo = serverUrlTo;
  1686. [_queueSelector addObject:metadataNet.selector];
  1687. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1688. }
  1689. // cyptated
  1690. if (metadata.cryptated == YES) {
  1691. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1692. metadataNet.action = actionMoveFileOrFolder;
  1693. metadataNet.directory = metadata.directory;
  1694. metadataNet.fileID = metadata.fileID;
  1695. metadataNet.directoryID = metadata.directoryID;
  1696. metadataNet.directoryIDTo = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrlTo];
  1697. metadataNet.fileNamePrint = metadata.fileNamePrint;
  1698. metadataNet.etag = metadata.etag;
  1699. metadataNet.serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1700. metadataNet.serverUrlTo = serverUrlTo;
  1701. // data
  1702. metadataNet.fileName = metadata.fileNameData;
  1703. metadataNet.fileNameTo = metadata.fileNameData;
  1704. metadataNet.selector = selectorMoveCrypto;
  1705. [_queueSelector addObject:metadataNet.selector];
  1706. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1707. // plist
  1708. metadataNet.fileName = metadata.fileName;
  1709. metadataNet.fileNameTo = metadata.fileName;
  1710. metadataNet.selector = selectorMovePlist;
  1711. [_queueSelector addObject:metadataNet.selector];
  1712. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1713. }
  1714. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_move_file_n_", nil), _numSelectedMetadatas - [_selectedMetadatas count] + 1, _numSelectedMetadatas] mode:MBProgressHUDModeIndeterminate color:nil];
  1715. }
  1716. }
  1717. - (void)moveServerUrlTo:(NSString *)serverUrlTo title:(NSString *)title selectedMetadatas:(NSArray *)selectedMetadatas
  1718. {
  1719. [_selectedMetadatas removeAllObjects];
  1720. [_queueSelector removeAllObjects];
  1721. _selectedMetadatas = [[NSMutableArray alloc] initWithArray:selectedMetadatas];
  1722. _numSelectedMetadatas = [_selectedMetadatas count];
  1723. [self performSelectorOnMainThread:@selector(moveFileOrFolder:) withObject:serverUrlTo waitUntilDone:NO];
  1724. [self tableViewSelect:NO];
  1725. }
  1726. - (void)moveOpenWindow:(NSArray *)indexPaths
  1727. {
  1728. UINavigationController* navigationController = [[UIStoryboard storyboardWithName:@"CCMove" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMove"];
  1729. CCMove *viewController = (CCMove *)navigationController.topViewController;
  1730. viewController.delegate = self;
  1731. viewController.move.title = NSLocalizedString(@"_move_", nil);
  1732. viewController.selectedMetadatas = [self getMetadatasFromSelectedRows:indexPaths];
  1733. viewController.tintColor = [NCBrandColor sharedInstance].navigationBarText;
  1734. viewController.barTintColor = [NCBrandColor sharedInstance].brand;
  1735. viewController.tintColorTitle = [NCBrandColor sharedInstance].navigationBarText;
  1736. viewController.networkingOperationQueue = app.netQueue;
  1737. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  1738. [self presentViewController:navigationController animated:YES completion:nil];
  1739. }
  1740. #pragma --------------------------------------------------------------------------------------------
  1741. #pragma mark ===== Create folder =====
  1742. #pragma --------------------------------------------------------------------------------------------
  1743. - (void)createFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1744. {
  1745. [_hud hideHud];
  1746. if (message)
  1747. [app messageNotification:@"_create_folder_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1748. }
  1749. - (void)createFolderSuccess:(CCMetadataNet *)metadataNet
  1750. {
  1751. [_hud hideHud];
  1752. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", metadataNet.serverUrl, metadataNet.fileName];
  1753. (void)[[NCManageDatabase sharedInstance] addDirectoryWithServerUrl:newDirectory permissions:@""];
  1754. // Load Folder or the Datasource
  1755. if ([metadataNet.selectorPost isEqualToString:selectorReadFolderForced]) {
  1756. [self readFolderWithForced:YES serverUrl:metadataNet.serverUrl];
  1757. } else {
  1758. [self reloadDatasource:metadataNet.serverUrl fileID:metadataNet.fileID selector:metadataNet.selector];
  1759. }
  1760. }
  1761. - (void)createFolder:(NSString *)fileNameFolder autoUploadDirectory:(BOOL)autoUploadDirectory
  1762. {
  1763. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1764. fileNameFolder = [CCUtility removeForbiddenCharactersServer:fileNameFolder];
  1765. if (![fileNameFolder length]) return;
  1766. if (autoUploadDirectory) metadataNet.serverUrl = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:app.activeUrl];
  1767. else metadataNet.serverUrl = _serverUrl;
  1768. metadataNet.action = actionCreateFolder;
  1769. if (autoUploadDirectory)
  1770. metadataNet.options = @"folderAutoUpload";
  1771. metadataNet.fileName = fileNameFolder;
  1772. metadataNet.selector = selectorCreateFolder;
  1773. metadataNet.selectorPost = selectorReadFolderForced;
  1774. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1775. if (!autoUploadDirectory)
  1776. [_hud visibleHudTitle:NSLocalizedString(@"_create_folder_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1777. }
  1778. - (void)createFolderEncrypted:(NSString *)fileNameFolder
  1779. {
  1780. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1781. NSString *fileNamePlist;
  1782. fileNameFolder = [CCUtility removeForbiddenCharactersServer:fileNameFolder];
  1783. if (![fileNameFolder length]) return;
  1784. NSString *title = [AESCrypt encrypt:fileNameFolder password:[[CCCrypto sharedManager] getKeyPasscode:[CCUtility getUUID]]];
  1785. fileNamePlist = [[CCCrypto sharedManager] createFilenameEncryptor:fileNameFolder uuid:[CCUtility getUUID]];
  1786. [[CCCrypto sharedManager] createFilePlist:[NSTemporaryDirectory() stringByAppendingString:fileNamePlist] title:title len:0 directory:true uuid:[CCUtility getUUID] nameCurrentDevice:[CCUtility getNameCurrentDevice] icon:@""];
  1787. // Create folder
  1788. metadataNet.action = actionCreateFolder;
  1789. metadataNet.fileName = fileNamePlist;
  1790. metadataNet.priority = NSOperationQueuePriorityVeryHigh;
  1791. metadataNet.selector = selectorCreateFolder;
  1792. metadataNet.serverUrl = _serverUrl;
  1793. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1794. // upload plist file
  1795. metadataNet.action = actionUploadOnlyPlist;
  1796. metadataNet.fileName = [fileNamePlist stringByAppendingString:@".plist"];
  1797. metadataNet.priority = NSOperationQueuePriorityVeryLow;
  1798. metadataNet.selectorPost = selectorReadFolderForced;
  1799. metadataNet.serverUrl = _serverUrl;
  1800. metadataNet.session = k_upload_session_foreground;
  1801. metadataNet.taskStatus = k_taskStatusResume;
  1802. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1803. [_hud visibleHudTitle:NSLocalizedString(@"_create_folder_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1804. }
  1805. - (void)createFolderAutoUpload
  1806. {
  1807. NSString *autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  1808. [self createFolder:autoUploadFileName autoUploadDirectory:YES];
  1809. }
  1810. #pragma --------------------------------------------------------------------------------------------
  1811. #pragma mark ===== Encrypted / Decrypted Folder =====
  1812. #pragma --------------------------------------------------------------------------------------------
  1813. - (void)encyptedDecryptedFolder
  1814. {
  1815. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  1816. if (_metadata.cryptated) {
  1817. // DECRYPTED
  1818. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1819. //-------------------------- RENAME -------------------------------------------//
  1820. metadataNet.action = actionMoveFileOrFolder;
  1821. metadataNet.fileID = _metadata.fileID;
  1822. metadataNet.fileName = _metadata.fileNameData;
  1823. metadataNet.fileNameTo = _metadata.fileNamePrint;
  1824. metadataNet.fileNamePrint = _metadata.fileNamePrint;
  1825. metadataNet.priority = NSOperationQueuePriorityVeryHigh;
  1826. metadataNet.selector = selectorRename;
  1827. metadataNet.serverUrl = serverUrl;
  1828. metadataNet.serverUrlTo = serverUrl;
  1829. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1830. //-------------------------- DELETE -------------------------------------------//
  1831. metadataNet.action = actionDeleteFileDirectory;
  1832. metadataNet.fileID = _metadata.fileID;
  1833. metadataNet.fileName = _metadata.fileName;
  1834. metadataNet.fileNamePrint = _metadata.fileNamePrint;
  1835. metadataNet.priority = NSOperationQueuePriorityVeryLow;
  1836. metadataNet.selector = selectorDeletePlist;
  1837. metadataNet.selectorPost = selectorReadFolderForced;
  1838. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1839. } else {
  1840. // ENCRYPTED
  1841. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1842. // Create File Plist
  1843. NSString *fileNameCrypto = [[CCCrypto sharedManager] createFileDirectoryPlist:_metadata];
  1844. //-------------------------- RENAME -------------------------------------------//
  1845. metadataNet.action = actionMoveFileOrFolder;
  1846. metadataNet.fileID = _metadata.fileID;
  1847. metadataNet.fileName = _metadata.fileName;
  1848. metadataNet.fileNamePrint = _metadata.fileNamePrint;
  1849. metadataNet.fileNameTo = fileNameCrypto;
  1850. metadataNet.priority = NSOperationQueuePriorityVeryHigh;
  1851. metadataNet.selector = selectorRename;
  1852. metadataNet.serverUrl = serverUrl;
  1853. metadataNet.serverUrlTo = serverUrl;
  1854. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1855. //-------------------------- UPLOAD -------------------------------------------//
  1856. metadataNet.action = actionUploadOnlyPlist;
  1857. metadataNet.fileName = [fileNameCrypto stringByAppendingString:@".plist"];
  1858. metadataNet.priority = NSOperationQueuePriorityVeryLow;
  1859. metadataNet.selectorPost = selectorReadFolderForced;
  1860. metadataNet.serverUrl = serverUrl;
  1861. metadataNet.session = k_upload_session_foreground;
  1862. metadataNet.taskStatus = k_taskStatusResume;
  1863. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1864. }
  1865. }
  1866. #pragma --------------------------------------------------------------------------------------------
  1867. #pragma mark ===== Encrypted/Decrypted File =====
  1868. #pragma --------------------------------------------------------------------------------------------
  1869. - (void)encryptedSelectedFiles
  1870. {
  1871. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  1872. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1873. for (tableMetadata *metadata in selectedMetadatas) {
  1874. if (metadata.cryptated == NO && metadata.directory == NO)
  1875. [metadatas addObject:metadata];
  1876. }
  1877. if ([metadatas count] > 0) {
  1878. NSLog(@"[LOG] Start encrypted selected files ...");
  1879. for (tableMetadata* metadata in metadatas) {
  1880. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1881. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorEncryptFile selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  1882. }
  1883. }
  1884. [self tableViewSelect:NO];
  1885. }
  1886. - (void)decryptedSelectedFiles
  1887. {
  1888. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  1889. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1890. for (tableMetadata *metadata in selectedMetadatas) {
  1891. if (metadata.cryptated == YES && metadata.directory == NO && [metadata.model length] == 0)
  1892. [metadatas addObject:metadata];
  1893. }
  1894. if ([metadatas count] > 0) {
  1895. NSLog(@"[LOG] Start decrypted selected files ...");
  1896. for (tableMetadata* metadata in metadatas) {
  1897. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1898. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorDecryptFile selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  1899. }
  1900. }
  1901. [self tableViewSelect:NO];
  1902. }
  1903. - (void)cmdEncryptedDecryptedFile
  1904. {
  1905. NSString *selector;
  1906. if (_metadata.cryptated == YES) selector = selectorDecryptFile;
  1907. if (_metadata.cryptated == NO) selector = selectorEncryptFile;
  1908. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  1909. [[CCNetworking sharedNetworking] downloadFile:_metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selector selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  1910. }
  1911. - (void)encryptedFile:(tableMetadata *)metadata
  1912. {
  1913. NSString *fileNameFrom = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID];
  1914. NSString *fileNameTo = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileNamePrint];
  1915. [[NSFileManager defaultManager] copyItemAtPath:fileNameFrom toPath:fileNameTo error:nil];
  1916. if ([[NSFileManager defaultManager] fileExistsAtPath:fileNameTo]) {
  1917. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1918. dispatch_async(dispatch_get_main_queue(), ^{
  1919. [[CCNetworking sharedNetworking] uploadFile:metadata.fileName serverUrl:serverUrl cryptated:YES onlyPlist:NO session:k_upload_session taskStatus:k_taskStatusResume selector:nil selectorPost:nil errorCode:0 delegate:nil];
  1920. [self performSelector:@selector(reloadDatasource) withObject:nil];
  1921. });
  1922. } else {
  1923. [app messageNotification:@"_encrypted_selected_files_" description:@"_file_not_present_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1924. }
  1925. }
  1926. - (void)decryptedFile:(tableMetadata *)metadata
  1927. {
  1928. NSString *fileNameFrom = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID];
  1929. NSString *fileNameTo = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileNamePrint];
  1930. [[NSFileManager defaultManager] copyItemAtPath:fileNameFrom toPath:fileNameTo error:nil];
  1931. if ([[NSFileManager defaultManager] fileExistsAtPath:fileNameTo]) {
  1932. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1933. dispatch_async(dispatch_get_main_queue(), ^{
  1934. [[CCNetworking sharedNetworking] uploadFile:metadata.fileNamePrint serverUrl:serverUrl cryptated:NO onlyPlist:NO session:k_upload_session taskStatus:k_taskStatusResume selector:nil selectorPost:nil errorCode:0 delegate:nil];
  1935. [self performSelector:@selector(reloadDatasource) withObject:nil];
  1936. });
  1937. } else {
  1938. [app messageNotification:@"_decrypted_selected_files_" description:@"_file_not_present_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1939. }
  1940. }
  1941. #pragma --------------------------------------------------------------------------------------------
  1942. #pragma mark ===== Progress & Task Button =====
  1943. #pragma --------------------------------------------------------------------------------------------
  1944. - (void)triggerProgressTask:(NSNotification *)notification
  1945. {
  1946. NSDictionary *dict = notification.userInfo;
  1947. NSString *fileID = [dict valueForKey:@"fileID"];
  1948. NSString *serverUrl = [dict valueForKey:@"serverUrl"];
  1949. BOOL cryptated = [[dict valueForKey:@"cryptated"] boolValue];
  1950. float progress = [[dict valueForKey:@"progress"] floatValue];
  1951. // Check
  1952. if (!fileID)
  1953. return;
  1954. [app.listProgressMetadata setObject:[NSNumber numberWithFloat:progress] forKey:fileID];
  1955. if (![serverUrl isEqualToString:_serverUrl])
  1956. return;
  1957. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:fileID];
  1958. if (indexPath) {
  1959. CCTransfersCell *cell = (CCTransfersCell *)[self.tableView cellForRowAtIndexPath:indexPath];
  1960. if (cryptated) cell.progressView.progressTintColor = [NCBrandColor sharedInstance].cryptocloud;
  1961. else cell.progressView.progressTintColor = [UIColor blackColor];
  1962. cell.progressView.hidden = NO;
  1963. [cell.progressView setProgress:progress];
  1964. }
  1965. if (progress == 0)
  1966. [self.navigationController cancelCCProgress];
  1967. else
  1968. [self.navigationController setCCProgressPercentage:progress*100 andTintColor: [NCBrandColor sharedInstance].navigationBarProgress];
  1969. }
  1970. - (void)reloadTaskButton:(id)sender withEvent:(UIEvent *)event
  1971. {
  1972. UITouch * touch = [[event allTouches] anyObject];
  1973. CGPoint location = [touch locationInView:self.tableView];
  1974. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  1975. if (indexPath) {
  1976. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  1977. if (metadata)
  1978. [self reloadTaskButton:metadata];
  1979. }
  1980. }
  1981. - (void)reloadTaskButton:(tableMetadata *)metadata
  1982. {
  1983. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1984. __block NSURLSessionTask *findTask;
  1985. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  1986. NSInteger sessionTaskIdentifierPlist = metadata.sessionTaskIdentifierPlist;
  1987. NSString *fileID = metadata.fileID;
  1988. // DOWNLOAD
  1989. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  1990. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1991. for (NSURLSessionUploadTask *task in downloadTasks)
  1992. if (task.taskIdentifier == sessionTaskIdentifier || task.taskIdentifier == sessionTaskIdentifierPlist) {
  1993. findTask = task;
  1994. [app.listChangeTask setObject:@"reloadDownload" forKey:fileID];
  1995. [task cancel];
  1996. }
  1997. if (!findTask) {
  1998. [app.listChangeTask setObject:@"reloadDownload" forKey:fileID];
  1999. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  2000. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  2001. }
  2002. }];
  2003. }
  2004. // UPLOAD
  2005. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  2006. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2007. for (NSURLSessionUploadTask *task in uploadTasks)
  2008. if (task.taskIdentifier == sessionTaskIdentifier || task.taskIdentifier == sessionTaskIdentifierPlist) {
  2009. findTask = task;
  2010. [app.listChangeTask setObject:@"reloadUpload" forKey:fileID];
  2011. [task cancel];
  2012. }
  2013. if (!findTask) {
  2014. [app.listChangeTask setObject:@"reloadUpload" forKey:fileID];
  2015. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  2016. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  2017. }
  2018. }];
  2019. }
  2020. }
  2021. - (void)cancelTaskButton:(id)sender withEvent:(UIEvent *)event
  2022. {
  2023. UITouch * touch = [[event allTouches] anyObject];
  2024. CGPoint location = [touch locationInView:self.tableView];
  2025. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  2026. if (indexPath) {
  2027. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2028. if (metadata)
  2029. [self cancelTaskButton:metadata reloadTable:YES];
  2030. }
  2031. }
  2032. - (void)cancelTaskButton:(tableMetadata *)metadata reloadTable:(BOOL)reloadTable
  2033. {
  2034. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  2035. __block NSURLSessionTask *findTask;
  2036. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  2037. NSInteger sessionTaskIdentifierPlist = metadata.sessionTaskIdentifierPlist;
  2038. NSString *fileID = metadata.fileID;
  2039. // DOWNLOAD
  2040. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  2041. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2042. for (NSURLSessionTask *task in downloadTasks)
  2043. if (task.taskIdentifier == sessionTaskIdentifier || task.taskIdentifier == sessionTaskIdentifierPlist) {
  2044. findTask = task;
  2045. [app.listChangeTask setObject:@"cancelDownload" forKey:fileID];
  2046. [task cancel];
  2047. }
  2048. if (!findTask) {
  2049. [app.listChangeTask setObject:@"cancelDownload" forKey:fileID];
  2050. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  2051. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  2052. }
  2053. }];
  2054. }
  2055. // UPLOAD
  2056. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  2057. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2058. for (NSURLSessionUploadTask *task in uploadTasks)
  2059. if (task.taskIdentifier == sessionTaskIdentifier || task.taskIdentifier == sessionTaskIdentifierPlist) {
  2060. findTask = task;
  2061. [app.listChangeTask setObject:@"cancelUpload" forKey:fileID];
  2062. [task cancel];
  2063. }
  2064. if (!findTask) {
  2065. [app.listChangeTask setObject:@"cancelUpload" forKey:fileID];
  2066. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  2067. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  2068. }
  2069. }];
  2070. }
  2071. }
  2072. - (void)stopTaskButton:(id)sender withEvent:(UIEvent *)event
  2073. {
  2074. UITouch * touch = [[event allTouches] anyObject];
  2075. CGPoint location = [touch locationInView:self.tableView];
  2076. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  2077. if (indexPath) {
  2078. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2079. if (metadata)
  2080. [self stopTaskButton:metadata];
  2081. }
  2082. }
  2083. - (void)stopTaskButton:(tableMetadata *)metadata
  2084. {
  2085. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  2086. __block NSURLSessionTask *findTask;
  2087. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  2088. NSInteger sessionTaskIdentifierPlist = metadata.sessionTaskIdentifierPlist;
  2089. NSString *fileID = metadata.fileID;
  2090. // UPLOAD
  2091. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  2092. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2093. for (NSURLSessionUploadTask *task in uploadTasks)
  2094. if (task.taskIdentifier == sessionTaskIdentifier || task.taskIdentifier == sessionTaskIdentifierPlist) {
  2095. [app.listChangeTask setObject:@"stopUpload" forKey:fileID];
  2096. findTask = task;
  2097. [task cancel];
  2098. }
  2099. if (!findTask) {
  2100. [app.listChangeTask setObject:@"stopUpload" forKey:fileID];
  2101. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  2102. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  2103. }
  2104. }];
  2105. }
  2106. }
  2107. #pragma --------------------------------------------------------------------------------------------
  2108. #pragma mark ===== Shared =====
  2109. #pragma --------------------------------------------------------------------------------------------
  2110. - (void)readSharedSuccess:(CCMetadataNet *)metadataNet items:(NSDictionary *)items openWindow:(BOOL)openWindow
  2111. {
  2112. [_hud hideHud];
  2113. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  2114. // change account ?
  2115. tableAccount *record = [[NCManageDatabase sharedInstance] getAccountActive];
  2116. if([record.account isEqualToString:metadataNet.account] == NO)
  2117. return;
  2118. NSArray *result = [[NCManageDatabase sharedInstance] updateShare:items activeUrl:appDelegate.activeUrl];
  2119. if (result) {
  2120. appDelegate.sharesLink = result[0];
  2121. appDelegate.sharesUserAndGroup = result[1];
  2122. }
  2123. if (openWindow) {
  2124. if (_shareOC) {
  2125. [_shareOC reloadData];
  2126. } else {
  2127. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataNet.fileID]];
  2128. // Apriamo la view
  2129. _shareOC = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareOC"];
  2130. _shareOC.delegate = self;
  2131. _shareOC.metadata = metadata;
  2132. _shareOC.serverUrl = metadataNet.serverUrl;
  2133. _shareOC.shareLink = [app.sharesLink objectForKey:metadata.fileID];
  2134. _shareOC.shareUserAndGroup = [app.sharesUserAndGroup objectForKey:metadata.fileID];
  2135. [_shareOC setModalPresentationStyle:UIModalPresentationFormSheet];
  2136. [self presentViewController:_shareOC animated:YES completion:nil];
  2137. }
  2138. }
  2139. [self tableViewReload];
  2140. }
  2141. - (void)shareFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2142. {
  2143. [_hud hideHud];
  2144. [app messageNotification:@"_share_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  2145. if (_shareOC)
  2146. [_shareOC reloadData];
  2147. [self tableViewReload];
  2148. if (errorCode == 401)
  2149. [self changePasswordAccount];
  2150. }
  2151. - (void)share:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password
  2152. {
  2153. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2154. metadataNet.action = actionShare;
  2155. metadataNet.fileID = metadata.fileID;
  2156. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:app.activeUrl];
  2157. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2158. metadataNet.password = password;
  2159. metadataNet.selector = selectorShare;
  2160. metadataNet.serverUrl = serverUrl;
  2161. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2162. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2163. }
  2164. - (void)unShareSuccess:(CCMetadataNet *)metadataNet
  2165. {
  2166. [_hud hideHud];
  2167. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  2168. // rimuoviamo la condivisione da db
  2169. NSArray *result = [[NCManageDatabase sharedInstance] unShare:metadataNet.share fileName:metadataNet.fileName serverUrl:metadataNet.serverUrl sharesLink:appDelegate.sharesLink sharesUserAndGroup:appDelegate.sharesUserAndGroup];
  2170. if (result) {
  2171. appDelegate.sharesLink = result[0];
  2172. appDelegate.sharesUserAndGroup = result[1];
  2173. }
  2174. if (_shareOC)
  2175. [_shareOC reloadData];
  2176. [self tableViewReload];
  2177. }
  2178. - (void)unShare:(NSString *)share metadata:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl
  2179. {
  2180. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2181. metadataNet.action = actionUnShare;
  2182. metadataNet.fileID = metadata.fileID;
  2183. metadataNet.fileName = metadata.fileName;
  2184. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2185. metadataNet.selector = selectorUnshare;
  2186. metadataNet.serverUrl = serverUrl;
  2187. metadataNet.share = share;
  2188. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2189. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2190. }
  2191. - (void)updateShare:(NSString *)share metadata:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password expirationTime:(NSString *)expirationTime permission:(NSInteger)permission
  2192. {
  2193. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2194. metadataNet.action = actionUpdateShare;
  2195. metadataNet.fileID = metadata.fileID;
  2196. metadataNet.expirationTime = expirationTime;
  2197. metadataNet.password = password;
  2198. metadataNet.selector = selectorUpdateShare;
  2199. metadataNet.serverUrl = serverUrl;
  2200. metadataNet.share = share;
  2201. metadataNet.sharePermission = permission;
  2202. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2203. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2204. }
  2205. - (void)getUserAndGroupSuccess:(CCMetadataNet *)metadataNet items:(NSArray *)items
  2206. {
  2207. [_hud hideHud];
  2208. if (_shareOC)
  2209. [_shareOC reloadUserAndGroup:items];
  2210. }
  2211. - (void)getUserAndGroupFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2212. {
  2213. [_hud hideHud];
  2214. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  2215. }
  2216. - (void)getUserAndGroup:(NSString *)find
  2217. {
  2218. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2219. metadataNet.action = actionGetUserAndGroup;
  2220. metadataNet.options = find;
  2221. metadataNet.selector = selectorGetUserAndGroup;
  2222. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2223. [_hud visibleIndeterminateHud];
  2224. }
  2225. - (void)shareUserAndGroup:(NSString *)user shareeType:(NSInteger)shareeType permission:(NSInteger)permission metadata:(tableMetadata *)metadata directoryID:(NSString *)directoryID serverUrl:(NSString *)serverUrl
  2226. {
  2227. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2228. metadataNet.action = actionShareWith;
  2229. metadataNet.fileID = metadata.fileID;
  2230. metadataNet.directoryID = directoryID;
  2231. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:app.activeUrl];
  2232. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2233. metadataNet.serverUrl = serverUrl;
  2234. metadataNet.selector = selectorShare;
  2235. metadataNet.share = user;
  2236. metadataNet.shareeType = shareeType;
  2237. metadataNet.sharePermission = permission;
  2238. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2239. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2240. }
  2241. - (void)openWindowShare:(tableMetadata *)metadata
  2242. {
  2243. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2244. metadataNet.action = actionReadShareServer;
  2245. metadataNet.fileID = metadata.fileID;
  2246. metadataNet.fileName = metadata.fileName;
  2247. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2248. metadataNet.selector = selectorOpenWindowShare;
  2249. metadataNet.serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2250. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2251. [_hud visibleIndeterminateHud];
  2252. }
  2253. - (void)tapActionShared:(UITapGestureRecognizer *)tapGesture
  2254. {
  2255. CGPoint location = [tapGesture locationInView:self.tableView];
  2256. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  2257. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2258. if (metadata)
  2259. [self openWindowShare:metadata];
  2260. }
  2261. - (void)tapActionConnectionMounted:(UITapGestureRecognizer *)tapGesture
  2262. {
  2263. CGPoint location = [tapGesture locationInView:self.tableView];
  2264. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  2265. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2266. if (metadata) {
  2267. CCShareInfoCMOC *vc = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareInfoCMOC"];
  2268. vc.metadata = metadata;
  2269. [vc setModalPresentationStyle:UIModalPresentationFormSheet];
  2270. [self presentViewController:vc animated:YES completion:nil];
  2271. }
  2272. }
  2273. #pragma --------------------------------------------------------------------------------------------
  2274. #pragma mark ===== Favorite =====
  2275. #pragma --------------------------------------------------------------------------------------------
  2276. - (void)settingFavoriteSuccess:(CCMetadataNet *)metadataNet
  2277. {
  2278. _dateReadDataSource = nil;
  2279. [[NCManageDatabase sharedInstance] setMetadataFavoriteWithFileID:metadataNet.fileID favorite:[metadataNet.options boolValue]];
  2280. if (_isSearchMode)
  2281. [self readFolderWithForced:YES serverUrl:metadataNet.serverUrl];
  2282. else
  2283. [self reloadDatasource:metadataNet.serverUrl fileID:metadataNet.fileID selector:metadataNet.selector];
  2284. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataNet.fileID]];
  2285. if (metadata.directory && metadata.favorite) {
  2286. NSString *dir = [CCUtility stringAppendServerUrl:metadataNet.serverUrl addFileName:metadata.fileNameData];
  2287. [[CCSynchronize sharedSynchronize] addFavoriteFolder:dir];
  2288. }
  2289. }
  2290. - (void)settingFavoriteFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2291. {
  2292. }
  2293. - (void)addFavorite:(tableMetadata *)metadata
  2294. {
  2295. if (metadata.directory) {
  2296. [[CCActions sharedInstance] settingFavorite:metadata favorite:YES delegate:self];
  2297. } else {
  2298. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2299. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorAddFavorite selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2300. }
  2301. }
  2302. - (void)removeFavorite:(tableMetadata *)metadata
  2303. {
  2304. [[CCActions sharedInstance] settingFavorite:metadata favorite:NO delegate:self];
  2305. }
  2306. #pragma --------------------------------------------------------------------------------------------
  2307. #pragma mark ===== Local =====
  2308. #pragma --------------------------------------------------------------------------------------------
  2309. - (void)addLocal:(tableMetadata *)metadata
  2310. {
  2311. if (metadata.errorPasscode || !metadata.uuid) return;
  2312. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2313. if ([metadata.type isEqualToString: k_metadataType_file])
  2314. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorAddLocal selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2315. if ([metadata.type isEqualToString: k_metadataType_template]) {
  2316. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileName] toPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryLocal], metadata.fileName]];
  2317. [app messageNotification:@"_add_local_" description:@"_file_saved_local_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess errorCode:0];
  2318. }
  2319. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2320. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2321. }
  2322. #pragma --------------------------------------------------------------------------------------------
  2323. #pragma mark ===== Open in... =====
  2324. #pragma --------------------------------------------------------------------------------------------
  2325. - (void)openIn:(tableMetadata *)metadata
  2326. {
  2327. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2328. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorOpenIn selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2329. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2330. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2331. }
  2332. #pragma --------------------------------------------------------------------------------------------
  2333. #pragma mark ===== Remove Local File =====
  2334. #pragma --------------------------------------------------------------------------------------------
  2335. - (void)removeLocalFile:(tableMetadata *)metadata
  2336. {
  2337. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2338. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadata.fileID]];
  2339. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] error:nil];
  2340. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:nil];
  2341. }
  2342. #pragma --------------------------------------------------------------------------------------------
  2343. #pragma mark ===== Order Table & GroupBy & DirectoryOnTop =====
  2344. #pragma --------------------------------------------------------------------------------------------
  2345. - (void)orderTable:(NSString *)order
  2346. {
  2347. [CCUtility setOrderSettings:order];
  2348. // Clear data-read of DataSource
  2349. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2350. }
  2351. - (void)ascendingTable:(BOOL)ascending
  2352. {
  2353. [CCUtility setAscendingSettings:ascending];
  2354. // Clear data-read of DataSource
  2355. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2356. }
  2357. - (void)directoryOnTop:(BOOL)directoryOnTop
  2358. {
  2359. [CCUtility setDirectoryOnTop:directoryOnTop];
  2360. // Clear data-read of DataSource
  2361. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2362. }
  2363. - (void)tableGroupBy:(NSString *)groupBy
  2364. {
  2365. [CCUtility setGroupBySettings:groupBy];
  2366. // Clear data-read of DataSource
  2367. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2368. }
  2369. #pragma --------------------------------------------------------------------------------------------
  2370. #pragma mark ==== Menu LOGO ====
  2371. #pragma --------------------------------------------------------------------------------------------
  2372. - (void)menuLogo
  2373. {
  2374. if (app.reSelectMenu.isOpen || app.reMainMenu.isOpen)
  2375. return;
  2376. // Brand
  2377. if ([NCBrandOptions sharedInstance].disable_multiaccount)
  2378. return;
  2379. if ([app.netQueue operationCount] > 0 || [app.netQueueDownload operationCount] > 0 || [app.netQueueDownloadWWan operationCount] > 0 || [app.netQueueUpload operationCount] > 0 || [app.netQueueUploadWWan operationCount] > 0 || [[NCManageDatabase sharedInstance] countAutomaticUploadWithSession:nil] > 0) {
  2380. [app messageNotification:@"_transfers_in_queue_" description:nil visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:0];
  2381. return;
  2382. }
  2383. NSArray *listAccount = [[NCManageDatabase sharedInstance] getAccounts];
  2384. NSMutableArray *menuArray = [NSMutableArray new];
  2385. for (NSString *account in listAccount) {
  2386. if ([account isEqualToString:app.activeAccount]) continue;
  2387. CCMenuItem *item = [[CCMenuItem alloc] init];
  2388. item.title = [account stringByTruncatingToWidth:self.view.bounds.size.width - 100 withFont:[UIFont systemFontOfSize:12.0] atEnd:YES];
  2389. item.argument = account;
  2390. item.image = [UIImage imageNamed:@"menuLogoUser"];
  2391. item.target = self;
  2392. item.action = @selector(changeDefaultAccount:);
  2393. [menuArray addObject:item];
  2394. }
  2395. if ([menuArray count] == 0)
  2396. return;
  2397. OptionalConfiguration options;
  2398. Color textColor, backgroundColor;
  2399. textColor.R = 0;
  2400. textColor.G = 0;
  2401. textColor.B = 0;
  2402. backgroundColor.R = 1;
  2403. backgroundColor.G = 1;
  2404. backgroundColor.B = 1;
  2405. NSInteger originY = 60;
  2406. options.arrowSize = 9;
  2407. options.marginXSpacing = 7;
  2408. options.marginYSpacing = 10;
  2409. options.intervalSpacing = 20;
  2410. options.menuCornerRadius = 6.5;
  2411. options.maskToBackground = NO;
  2412. options.shadowOfMenu = YES;
  2413. options.hasSeperatorLine = YES;
  2414. options.seperatorLineHasInsets = YES;
  2415. options.textColor = textColor;
  2416. options.menuBackgroundColor = backgroundColor;
  2417. CGRect rect = self.view.frame;
  2418. rect.origin.y = rect.origin.y + originY;
  2419. rect.size.height = rect.size.height - originY;
  2420. [CCMenuAccount setTitleFont:[UIFont systemFontOfSize:12.0]];
  2421. [CCMenuAccount showMenuInView:self.navigationController.view fromRect:rect menuItems:menuArray withOptions:options];
  2422. }
  2423. - (void)changeDefaultAccount:(CCMenuItem *)sender
  2424. {
  2425. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:NO];
  2426. // STOP, erase all in queue networking
  2427. [app cancelAllOperations];
  2428. [[CCNetworking sharedNetworking] settingSessionsDownload:YES upload:YES taskStatus:k_taskStatusCancel activeAccount:app.activeAccount activeUser:app.activeUser activeUrl:app.activeUrl];
  2429. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  2430. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] setAccountActive:[sender argument]];
  2431. if (tableAccount)
  2432. [app settingActiveAccount:tableAccount.account activeUrl:tableAccount.url activeUser:tableAccount.user activePassword:tableAccount.password];
  2433. // go to home sweet home
  2434. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"initializeMain" object:nil];
  2435. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  2436. });
  2437. }
  2438. #pragma --------------------------------------------------------------------------------------------
  2439. #pragma mark ==== ReMenu ====
  2440. #pragma --------------------------------------------------------------------------------------------
  2441. - (void)createReMenuBackgroundView:(REMenu *)menu
  2442. {
  2443. __block CGFloat navigationBarH = self.navigationController.navigationBar.frame.size.height + [UIApplication sharedApplication].statusBarFrame.size.height;
  2444. _reMenuBackgroundView.frame = CGRectMake(0, navigationBarH, self.view.frame.size.width, self.view.frame.size.height);
  2445. [UIView animateWithDuration:0.2 animations:^{
  2446. float height = (self.view.frame.size.height + navigationBarH) - (menu.menuView.frame.size.height - self.navigationController.navigationBar.frame.size.height + 3);
  2447. if (height < self.tabBarController.tabBar.frame.size.height)
  2448. height = self.tabBarController.tabBar.frame.size.height;
  2449. _reMenuBackgroundView.frame = CGRectMake(0, self.view.frame.size.height + navigationBarH, self.view.frame.size.width, - height);
  2450. [self.tabBarController.view addSubview:_reMenuBackgroundView];
  2451. }];
  2452. }
  2453. - (void)createReMainMenu
  2454. {
  2455. NSString *ordinamento;
  2456. NSString *groupBy = _directoryGroupBy;
  2457. __block NSString *nuovoOrdinamento;
  2458. NSString *titoloNuovo, *titoloAttuale;
  2459. BOOL ascendente;
  2460. __block BOOL nuovoAscendente;
  2461. UIImage *image;
  2462. // ITEM SELECT ----------------------------------------------------------------------------------------------------
  2463. app.selezionaItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_select_", nil)subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"seleziona"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2464. if ([_sectionDataSource.allRecordsDataSource count] > 0) {
  2465. [self tableViewSelect:YES];
  2466. }
  2467. }];
  2468. // ITEM ORDER ----------------------------------------------------------------------------------------------------
  2469. ordinamento = _directoryOrder;
  2470. if ([ordinamento isEqualToString:@"fileName"]) {
  2471. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdeyByDate"] color:[NCBrandColor sharedInstance].brand];
  2472. titoloNuovo = NSLocalizedString(@"_order_by_date_", nil);
  2473. titoloAttuale = NSLocalizedString(@"_current_order_name_", nil);
  2474. nuovoOrdinamento = @"date";
  2475. }
  2476. if ([ordinamento isEqualToString:@"date"]) {
  2477. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrderByFileName"] color:[NCBrandColor sharedInstance].brand];
  2478. titoloNuovo = NSLocalizedString(@"_order_by_name_", nil);
  2479. titoloAttuale = NSLocalizedString(@"_current_order_date_", nil);
  2480. nuovoOrdinamento = @"fileName";
  2481. }
  2482. app.ordinaItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:titoloAttuale image:image highlightedImage:nil action:^(REMenuItem *item) {
  2483. [self orderTable:nuovoOrdinamento];
  2484. }];
  2485. // ITEM ASCENDING -----------------------------------------------------------------------------------------------------
  2486. ascendente = [CCUtility getAscendingSettings];
  2487. if (ascendente) {
  2488. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdinamentoDiscendente"] color:[NCBrandColor sharedInstance].brand];
  2489. titoloNuovo = NSLocalizedString(@"_sort_descending_", nil);
  2490. titoloAttuale = NSLocalizedString(@"_current_sort_ascending_", nil);
  2491. nuovoAscendente = false;
  2492. }
  2493. if (!ascendente) {
  2494. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdinamentoAscendente"] color:[NCBrandColor sharedInstance].brand];
  2495. titoloNuovo = NSLocalizedString(@"_sort_ascending_", nil);
  2496. titoloAttuale = NSLocalizedString(@"_current_sort_descending_", nil);
  2497. nuovoAscendente = true;
  2498. }
  2499. app.ascendenteItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:titoloAttuale image:image highlightedImage:nil action:^(REMenuItem *item) {
  2500. [self ascendingTable:nuovoAscendente];
  2501. }];
  2502. // ITEM ALPHABETIC -----------------------------------------------------------------------------------------------------
  2503. if ([groupBy isEqualToString:@"alphabetic"]) { titoloNuovo = NSLocalizedString(@"_group_alphabetic_yes_", nil); }
  2504. else { titoloNuovo = NSLocalizedString(@"_group_alphabetic_no_", nil); }
  2505. app.alphabeticItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByAlphabetic"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2506. if ([groupBy isEqualToString:@"alphabetic"]) [self tableGroupBy:@"none"];
  2507. else [self tableGroupBy:@"alphabetic"];
  2508. }];
  2509. // ITEM TYPEFILE -------------------------------------------------------------------------------------------------------
  2510. if ([groupBy isEqualToString:@"typefile"]) { titoloNuovo = NSLocalizedString(@"_group_typefile_yes_", nil); }
  2511. else { titoloNuovo = NSLocalizedString(@"_group_typefile_no_", nil); }
  2512. app.typefileItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByTypeFile"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2513. if ([groupBy isEqualToString:@"typefile"]) [self tableGroupBy:@"none"];
  2514. else [self tableGroupBy:@"typefile"];
  2515. }];
  2516. // ITEM DATE -------------------------------------------------------------------------------------------------------
  2517. if ([groupBy isEqualToString:@"date"]) { titoloNuovo = NSLocalizedString(@"_group_date_yes_", nil); }
  2518. else { titoloNuovo = NSLocalizedString(@"_group_date_no_", nil); }
  2519. app.dateItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByDate"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2520. if ([groupBy isEqualToString:@"date"]) [self tableGroupBy:@"none"];
  2521. else [self tableGroupBy:@"date"];
  2522. }];
  2523. // ITEM DIRECTORY ON TOP ------------------------------------------------------------------------------------------------
  2524. if ([CCUtility getDirectoryOnTop]) { titoloNuovo = NSLocalizedString(@"_directory_on_top_yes_", nil); }
  2525. else { titoloNuovo = NSLocalizedString(@"_directory_on_top_no_", nil); }
  2526. app.directoryOnTopItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"menuDirectoryOnTop"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2527. if ([CCUtility getDirectoryOnTop]) [self directoryOnTop:NO];
  2528. else [self directoryOnTop:YES];
  2529. }];
  2530. // REMENU --------------------------------------------------------------------------------------------------------------
  2531. app.reMainMenu = [[REMenu alloc] initWithItems:@[app.selezionaItem, app.ordinaItem, app.ascendenteItem, app.alphabeticItem, app.typefileItem, app.dateItem, app.directoryOnTopItem]];
  2532. app.reMainMenu.imageOffset = CGSizeMake(5, -1);
  2533. app.reMainMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  2534. app.reMainMenu.imageOffset = CGSizeMake(0, 0);
  2535. app.reMainMenu.waitUntilAnimationIsComplete = NO;
  2536. app.reMainMenu.separatorHeight = 0.5;
  2537. app.reMainMenu.separatorColor = [NCBrandColor sharedInstance].seperator;
  2538. app.reMainMenu.backgroundColor = [NCBrandColor sharedInstance].menuBackground;
  2539. app.reMainMenu.textColor = [UIColor blackColor];
  2540. app.reMainMenu.textAlignment = NSTextAlignmentLeft;
  2541. app.reMainMenu.textShadowColor = nil;
  2542. app.reMainMenu.textOffset = CGSizeMake(50, 0.0);
  2543. app.reMainMenu.font = [UIFont systemFontOfSize:14.0];
  2544. app.reMainMenu.highlightedBackgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  2545. app.reMainMenu.highlightedSeparatorColor = nil;
  2546. app.reMainMenu.highlightedTextColor = [UIColor blackColor];
  2547. app.reMainMenu.highlightedTextShadowColor = nil;
  2548. app.reMainMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2549. app.reMainMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1];
  2550. app.reMainMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2551. app.reMainMenu.subtitleTextShadowColor = nil;
  2552. app.reMainMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2553. app.reMainMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2554. app.reMainMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2555. app.reMainMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2556. app.reMainMenu.subtitleHighlightedTextShadowColor = nil;
  2557. app.reMainMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2558. app.reMainMenu.borderWidth = 0.3;
  2559. app.reMainMenu.borderColor = [UIColor lightGrayColor];
  2560. app.reMainMenu.animationDuration = 0.2;
  2561. app.reMainMenu.closeAnimationDuration = 0.2;
  2562. app.reMainMenu.bounce = NO;
  2563. [app.reMainMenu setClosePreparationBlock:^{
  2564. // Backgroun reMenu (Gesture)
  2565. [_reMenuBackgroundView removeFromSuperview];
  2566. [_reMenuBackgroundView removeGestureRecognizer:_singleFingerTap];
  2567. }];
  2568. }
  2569. - (void)toggleReMainMenu
  2570. {
  2571. if (app.reMainMenu.isOpen) {
  2572. [app.reMainMenu close];
  2573. } else {
  2574. [self createReMainMenu];
  2575. [app.reMainMenu showFromNavigationController:self.navigationController];
  2576. // Backgroun reMenu & (Gesture)
  2577. [self createReMenuBackgroundView:app.reMainMenu];
  2578. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReMainMenu)];
  2579. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2580. }
  2581. }
  2582. - (void)createReSelectMenu
  2583. {
  2584. // ITEM DELETE ------------------------------------------------------------------------------------------------------
  2585. app.deleteItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_delete_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"deleteSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2586. [self deleteSelectionFile];
  2587. }];
  2588. // ITEM MOVE ------------------------------------------------------------------------------------------------------
  2589. app.moveItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_move_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"moveSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2590. [self moveOpenWindow:[self.tableView indexPathsForSelectedRows]];
  2591. }];
  2592. if (app.isCryptoCloudMode) {
  2593. // ITEM ENCRYPTED ------------------------------------------------------------------------------------------------------
  2594. app.encryptItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_encrypted_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"encryptedSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2595. [self performSelector:@selector(encryptedSelectedFiles) withObject:nil];
  2596. }];
  2597. // ITEM DECRYPTED ----------------------------------------------------------------------------------------------------
  2598. app.decryptItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_decrypted_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"decryptedSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2599. [self performSelector:@selector(decryptedSelectedFiles) withObject:nil];
  2600. }];
  2601. }
  2602. // ITEM DOWNLOAD ----------------------------------------------------------------------------------------------------
  2603. app.downloadItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_download_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"downloadSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2604. [self downloadSelectedFiles];
  2605. }];
  2606. // ITEM SAVE IMAGE & VIDEO -------------------------------------------------------------------------------------------
  2607. app.saveItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_save_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"saveSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2608. [self saveSelectedFiles];
  2609. }];
  2610. // REMENU --------------------------------------------------------------------------------------------------------------
  2611. if (app.isCryptoCloudMode) {
  2612. app.reSelectMenu = [[REMenu alloc] initWithItems:@[app.deleteItem,app.moveItem, app.encryptItem, app.decryptItem, app.downloadItem, app.saveItem]];
  2613. } else {
  2614. app.reSelectMenu = [[REMenu alloc] initWithItems:@[app.deleteItem,app.moveItem, app.downloadItem, app.saveItem]];
  2615. }
  2616. app.reSelectMenu.imageOffset = CGSizeMake(5, -1);
  2617. app.reSelectMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  2618. app.reSelectMenu.imageOffset = CGSizeMake(0, 0);
  2619. app.reSelectMenu.waitUntilAnimationIsComplete = NO;
  2620. app.reSelectMenu.separatorHeight = 0.5;
  2621. app.reSelectMenu.separatorColor = [NCBrandColor sharedInstance].seperator;
  2622. app.reSelectMenu.backgroundColor = [NCBrandColor sharedInstance].menuBackground;
  2623. app.reSelectMenu.textColor = [UIColor blackColor];
  2624. app.reSelectMenu.textAlignment = NSTextAlignmentLeft;
  2625. app.reSelectMenu.textShadowColor = nil;
  2626. app.reSelectMenu.textOffset = CGSizeMake(50, 0.0);
  2627. app.reSelectMenu.font = [UIFont systemFontOfSize:14.0];
  2628. app.reSelectMenu.highlightedBackgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  2629. app.reSelectMenu.highlightedSeparatorColor = nil;
  2630. app.reSelectMenu.highlightedTextColor = [UIColor blackColor];
  2631. app.reSelectMenu.highlightedTextShadowColor = nil;
  2632. app.reSelectMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2633. app.reSelectMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1.000];
  2634. app.reSelectMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2635. app.reSelectMenu.subtitleTextShadowColor = nil;
  2636. app.reSelectMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2637. app.reSelectMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2638. app.reSelectMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2639. app.reSelectMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2640. app.reSelectMenu.subtitleHighlightedTextShadowColor = nil;
  2641. app.reSelectMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2642. app.reSelectMenu.borderWidth = 0.3;
  2643. app.reSelectMenu.borderColor = [UIColor lightGrayColor];
  2644. app.reSelectMenu.closeAnimationDuration = 0.2;
  2645. app.reSelectMenu.animationDuration = 0.2;
  2646. app.reSelectMenu.bounce = NO;
  2647. [app.reSelectMenu setClosePreparationBlock:^{
  2648. // Backgroun reMenu (Gesture)
  2649. [_reMenuBackgroundView removeFromSuperview];
  2650. [_reMenuBackgroundView removeGestureRecognizer:_singleFingerTap];
  2651. }];
  2652. }
  2653. - (void)toggleReSelectMenu
  2654. {
  2655. if (app.reSelectMenu.isOpen) {
  2656. [app.reSelectMenu close];
  2657. } else {
  2658. [self createReSelectMenu];
  2659. [app.reSelectMenu showFromNavigationController:self.navigationController];
  2660. // Backgroun reMenu & (Gesture)
  2661. [self createReMenuBackgroundView:app.reSelectMenu];
  2662. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReSelectMenu)];
  2663. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2664. }
  2665. }
  2666. #pragma --------------------------------------------------------------------------------------------
  2667. #pragma mark ===== Long Press Recognized Table View / Menu Controller =====
  2668. #pragma --------------------------------------------------------------------------------------------
  2669. - (void)onLongPressTableView:(UILongPressGestureRecognizer*)recognizer
  2670. {
  2671. if (recognizer.state == UIGestureRecognizerStateBegan) {
  2672. UITableView *tableView = (UITableView*)self.view;
  2673. CGPoint touchPoint = [recognizer locationInView:self.view];
  2674. NSIndexPath *indexPath = [tableView indexPathForRowAtPoint:touchPoint];
  2675. if (indexPath)
  2676. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  2677. else
  2678. _metadata = nil;
  2679. [self becomeFirstResponder];
  2680. UIMenuController *menuController = [UIMenuController sharedMenuController];
  2681. UIMenuItem *copyFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_file_", nil) action:@selector(copyFile:)];
  2682. UIMenuItem *copyFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_files_", nil) action:@selector(copyFiles:)];
  2683. UIMenuItem *openinFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_open_in_", nil) action:@selector(openinFile:)];
  2684. UIMenuItem *pasteFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_file_", nil) action:@selector(pasteFile:)];
  2685. UIMenuItem *pasteFileEncryptedItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_file_encrypted_", nil) action:@selector(pasteFileEncrypted:)];
  2686. UIMenuItem *pasteFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_files_", nil) action:@selector(pasteFiles:)];
  2687. UIMenuItem *pasteFilesEncryptedItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_files_encrypted_", nil) action:@selector(pasteFilesEncrypted:)];
  2688. if (app.isCryptoCloudMode)
  2689. [menuController setMenuItems:[NSArray arrayWithObjects:copyFileItem, copyFilesItem, openinFileItem, pasteFileItem, pasteFilesItem, pasteFileEncryptedItem, pasteFilesEncryptedItem, nil]];
  2690. else
  2691. [menuController setMenuItems:[NSArray arrayWithObjects:copyFileItem, copyFilesItem, openinFileItem, pasteFileItem, pasteFilesItem, nil]];
  2692. [menuController setTargetRect:CGRectMake(touchPoint.x, touchPoint.y, 0.0f, 0.0f) inView:tableView];
  2693. [menuController setMenuVisible:YES animated:YES];
  2694. }
  2695. }
  2696. - (BOOL)canBecomeFirstResponder
  2697. {
  2698. return YES;
  2699. }
  2700. - (BOOL)canPerformAction:(SEL)action withSender:(id)sender
  2701. {
  2702. // For copy file, copy files, Open in ... :
  2703. //
  2704. // NO Directory
  2705. // NO Error Passcode
  2706. // NO In Session mode (download/upload)
  2707. // NO Template
  2708. if (@selector(copyFile:) == action || @selector(openinFile:) == action) {
  2709. if (_isSelectedMode == NO && _metadata && !_metadata.directory && !_metadata.errorPasscode && [_metadata.session length] == 0 && ![_metadata.typeFile isEqualToString: k_metadataTypeFile_template]) {
  2710. // NO Cryptated with Title lenght = 0
  2711. if (!_metadata.cryptated || (_metadata.cryptated && _metadata.title.length > 0))
  2712. return YES;
  2713. }
  2714. return NO;
  2715. }
  2716. if (@selector(copyFiles:) == action) {
  2717. if (_isSelectedMode) {
  2718. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2719. for (tableMetadata *metadata in selectedMetadatas) {
  2720. if (!metadata.directory && !metadata.errorPasscode && metadata.session.length == 0 && ![metadata.typeFile isEqualToString: k_metadataTypeFile_template]) {
  2721. // NO Cryptated with Title lenght = 0
  2722. if (!metadata.cryptated || (metadata.cryptated && metadata.title.length > 0))
  2723. return YES;
  2724. }
  2725. }
  2726. }
  2727. return NO;
  2728. }
  2729. if (@selector(pasteFile:) == action || @selector(pasteFileEncrypted:) == action) {
  2730. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2731. NSArray *items = [pasteboard items];
  2732. if ([items count] == 1) {
  2733. // Value : (NSData) fileID
  2734. NSDictionary *dic = [items objectAtIndex:0];
  2735. NSData *dataEtag = [dic objectForKey: k_metadataKeyedUnarchiver];
  2736. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataEtag];
  2737. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  2738. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2739. if (directoryUser) {
  2740. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileID]])
  2741. return YES;
  2742. }
  2743. return NO;
  2744. } else return NO;
  2745. }
  2746. if (@selector(pasteFiles:) == action || @selector(pasteFilesEncrypted:) == action) {
  2747. BOOL isValid = NO;
  2748. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2749. NSArray *items = [pasteboard items];
  2750. if ([items count] <= 1) return NO;
  2751. for (NSDictionary *dic in items) {
  2752. // Value : (NSData) fileID
  2753. NSData *dataEtag = [dic objectForKey: k_metadataKeyedUnarchiver];
  2754. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataEtag];
  2755. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  2756. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2757. if (directoryUser) {
  2758. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileID]])
  2759. isValid = YES;
  2760. }
  2761. }
  2762. return isValid;
  2763. }
  2764. return NO;
  2765. }
  2766. /************************************ COPY ************************************/
  2767. - (void)copyFile:(id)sender
  2768. {
  2769. // Remove all item
  2770. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2771. pasteboard.items = [[NSArray alloc] init];
  2772. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser,_metadata.fileID]]) {
  2773. [self copyFileToPasteboard:_metadata];
  2774. } else {
  2775. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2776. [[CCNetworking sharedNetworking] downloadFile:_metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorLoadCopy selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2777. }
  2778. }
  2779. - (void)copyFiles:(id)sender
  2780. {
  2781. // Remove all item
  2782. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2783. pasteboard.items = [[NSArray alloc] init];
  2784. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2785. for (tableMetadata *metadata in selectedMetadatas) {
  2786. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID]]) {
  2787. [self copyFileToPasteboard:metadata];
  2788. } else {
  2789. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2790. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorLoadCopy selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2791. }
  2792. }
  2793. [self tableViewSelect:NO];
  2794. }
  2795. - (void)copyFileToPasteboard:(tableMetadata *)metadata
  2796. {
  2797. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2798. NSMutableArray *items = [[NSMutableArray alloc] initWithArray:pasteboard.items];
  2799. // Value : (NSData) fileID
  2800. NSDictionary *item = [NSDictionary dictionaryWithObjectsAndKeys:[NSKeyedArchiver archivedDataWithRootObject:metadata.fileID], k_metadataKeyedUnarchiver,nil];
  2801. [items addObject:item];
  2802. [pasteboard setItems:items];
  2803. }
  2804. /************************************ OPEN IN ... ************************************/
  2805. - (void)openinFile:(id)sender
  2806. {
  2807. [self openIn:_metadata];
  2808. }
  2809. /************************************ PASTE ************************************/
  2810. - (void)pasteFile:(id)sender
  2811. {
  2812. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2813. [self uploadFilePasteArray:[pasteboard items] cryptated:NO];
  2814. }
  2815. - (void)pasteFileEncrypted:(id)sender
  2816. {
  2817. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2818. [self uploadFilePasteArray:[pasteboard items] cryptated:YES];
  2819. }
  2820. - (void)pasteFiles:(id)sender
  2821. {
  2822. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2823. [self uploadFilePasteArray:[pasteboard items] cryptated:NO];
  2824. }
  2825. - (void)pasteFilesEncrypted:(id)sender
  2826. {
  2827. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2828. [self uploadFilePasteArray:[pasteboard items] cryptated:YES];
  2829. }
  2830. - (void)uploadFilePasteArray:(NSArray *)items cryptated:(BOOL)cryptated
  2831. {
  2832. for (NSDictionary *dic in items) {
  2833. // Value : (NSData) fileID
  2834. NSData *dataEtag = [dic objectForKey: k_metadataKeyedUnarchiver];
  2835. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataEtag];
  2836. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  2837. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  2838. if (!metadata || !account) return;
  2839. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2840. if (directoryUser) {
  2841. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileID]]) {
  2842. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, metadata.fileID] toPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileNamePrint]];
  2843. [[CCNetworking sharedNetworking] uploadFile:metadata.fileNamePrint serverUrl:_serverUrl cryptated:cryptated onlyPlist:NO session:k_upload_session taskStatus:k_taskStatusResume selector:nil selectorPost:nil errorCode:0 delegate:nil];
  2844. }
  2845. }
  2846. }
  2847. }
  2848. #pragma --------------------------------------------------------------------------------------------
  2849. #pragma mark ===== Lock Passcode =====
  2850. #pragma --------------------------------------------------------------------------------------------
  2851. - (NSUInteger)passcodeViewControllerNumberOfFailedAttempts:(CCBKPasscode *)aViewController
  2852. {
  2853. return _failedAttempts;
  2854. }
  2855. - (NSDate *)passcodeViewControllerLockUntilDate:(CCBKPasscode *)aViewController
  2856. {
  2857. return _lockUntilDate;
  2858. }
  2859. - (void)passcodeViewCloseButtonPressed:(id)sender
  2860. {
  2861. [self dismissViewControllerAnimated:YES completion:nil];
  2862. }
  2863. - (void)passcodeViewController:(CCBKPasscode *)aViewController authenticatePasscode:(NSString *)aPasscode resultHandler:(void (^)(BOOL))aResultHandler
  2864. {
  2865. if (aViewController.fromType == CCBKPasscodeFromLockScreen || aViewController.fromType == CCBKPasscodeFromLockDirectory || aViewController.fromType == CCBKPasscodeFromDisactivateDirectory ) {
  2866. if ([aPasscode isEqualToString:[CCUtility getBlockCode]]) {
  2867. _lockUntilDate = nil;
  2868. _failedAttempts = 0;
  2869. aResultHandler(YES);
  2870. } else aResultHandler(NO);
  2871. } else aResultHandler(YES);
  2872. }
  2873. - (void)passcodeViewController:(CCBKPasscode *)aViewController didFinishWithPasscode:(NSString *)aPasscode
  2874. {
  2875. [aViewController dismissViewControllerAnimated:YES completion:nil];
  2876. switch (aViewController.type) {
  2877. case BKPasscodeViewControllerCheckPasscodeType: {
  2878. if (aViewController.fromType == CCBKPasscodeFromPasscode) {
  2879. // verifichiamo se il passcode è corretto per il seguente file -> UUID
  2880. if ([[CCCrypto sharedManager] verifyPasscode:aPasscode uuid:_metadata.uuid text:_metadata.title]) {
  2881. // scriviamo il passcode
  2882. [CCUtility setKeyChainPasscodeForUUID:_metadata.uuid conPasscode:aPasscode];
  2883. [self readFolderWithForced:YES serverUrl:_serverUrl];
  2884. } else {
  2885. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_error_passcode_", nil) delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  2886. [alertView show];
  2887. }
  2888. }
  2889. if (aViewController.fromType == CCBKPasscodeFromLockDirectory) {
  2890. // possiamo procedere alla prossima directory
  2891. [self performSegueDirectoryWithControlPasscode:false];
  2892. // avviamo la sessione Passcode Lock con now
  2893. app.sessionePasscodeLock = [NSDate date];
  2894. }
  2895. // disattivazione lock cartella
  2896. if (aViewController.fromType == CCBKPasscodeFromDisactivateDirectory) {
  2897. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2898. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  2899. if (![[NCManageDatabase sharedInstance] setDirectoryLockWithServerUrl:lockServerUrl lock:NO]) {
  2900. [app messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  2901. }
  2902. [self.tableView reloadData];
  2903. }
  2904. }
  2905. break;
  2906. default:
  2907. break;
  2908. }
  2909. }
  2910. - (void)comandoLockPassword
  2911. {
  2912. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2913. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  2914. // se non è abilitato il Lock Passcode esci
  2915. if ([[CCUtility getBlockCode] length] == 0) {
  2916. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_warning_", nil) message:NSLocalizedString(@"_only_lock_passcode_", nil) delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  2917. [alertView show];
  2918. return;
  2919. }
  2920. // se è richiesta la disattivazione si chiede la password
  2921. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"serverUrl = %@", lockServerUrl]];
  2922. if (directory.lock) {
  2923. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  2924. viewController.delegate = self;
  2925. viewController.fromType = CCBKPasscodeFromDisactivateDirectory;
  2926. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  2927. viewController.inputViewTitlePassword = YES;
  2928. if ([CCUtility getSimplyBlockCode]) {
  2929. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  2930. viewController.passcodeInputView.maximumLength = 6;
  2931. } else {
  2932. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  2933. viewController.passcodeInputView.maximumLength = 64;
  2934. }
  2935. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  2936. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  2937. viewController.touchIDManager = touchIDManager;
  2938. viewController.title = NSLocalizedString(@"_passcode_protection_", nil);
  2939. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  2940. viewController.navigationItem.leftBarButtonItem.tintColor = [NCBrandColor sharedInstance].cryptocloud;
  2941. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  2942. [self presentViewController:navigationController animated:YES completion:nil];
  2943. return;
  2944. }
  2945. // ---------------- ACTIVATE PASSWORD
  2946. if ([[NCManageDatabase sharedInstance] setDirectoryLockWithServerUrl:lockServerUrl lock:YES]) {
  2947. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:_metadata.fileID];
  2948. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2949. } else {
  2950. [app messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  2951. }
  2952. }
  2953. #pragma mark -
  2954. #pragma --------------------------------------------------------------------------------------------
  2955. #pragma mark ===== Swipe Tablet -> menu =====
  2956. #pragma --------------------------------------------------------------------------------------------
  2957. // more
  2958. - (NSString *)tableView:(UITableView *)tableView titleForSwipeAccessoryButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
  2959. return NSLocalizedString(@"_more_", nil);
  2960. }
  2961. - (void)tableView:(UITableView *)tableView swipeAccessoryButtonPushedForRowAtIndexPath:(NSIndexPath *)indexPath
  2962. {
  2963. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  2964. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2965. NSString *titoloCriptaDecripta, *titoloLock, *titleFavorite;
  2966. if (_metadata.cryptated) titoloCriptaDecripta = [NSString stringWithFormat:NSLocalizedString(@"_decrypt_", nil)];
  2967. else titoloCriptaDecripta = [NSString stringWithFormat:NSLocalizedString(@"_encrypt_", nil)];
  2968. if (_metadata.favorite) {
  2969. titleFavorite = [NSString stringWithFormat:NSLocalizedString(@"_remove_favorites_", nil)];
  2970. } else {
  2971. titleFavorite = [NSString stringWithFormat:NSLocalizedString(@"_add_favorites_", nil)];
  2972. }
  2973. if (_metadata.directory) {
  2974. // calcolo lockServerUrl
  2975. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  2976. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"serverUrl = %@", lockServerUrl]];
  2977. if (directory.lock)
  2978. titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_remove_passcode_", nil)];
  2979. else
  2980. titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_protect_passcode_", nil)];
  2981. }
  2982. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", _metadata.fileID]];
  2983. /******************************************* AHKActionSheet *******************************************/
  2984. AHKActionSheet *actionSheet = [[AHKActionSheet alloc] initWithView:self.view title:nil];
  2985. actionSheet.animationDuration = 0.2;
  2986. actionSheet.blurRadius = 0.0f;
  2987. actionSheet.blurTintColor = [UIColor colorWithWhite:0.0f alpha:0.50f];
  2988. actionSheet.buttonHeight = 50.0;
  2989. actionSheet.cancelButtonHeight = 50.0f;
  2990. actionSheet.separatorHeight = 5.0f;
  2991. actionSheet.automaticallyTintButtonImages = @(NO);
  2992. actionSheet.encryptedButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[NCBrandColor sharedInstance].cryptocloud };
  2993. actionSheet.buttonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor blackColor] };
  2994. actionSheet.cancelButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[NCBrandColor sharedInstance].brand };
  2995. actionSheet.disableButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor blackColor] };
  2996. actionSheet.separatorColor = [NCBrandColor sharedInstance].seperator;
  2997. actionSheet.cancelButtonTitle = NSLocalizedString(@"_cancel_",nil);
  2998. /******************************************* DIRECTORY *******************************************/
  2999. if (_metadata.directory) {
  3000. BOOL lockDirectory = NO;
  3001. NSString *dirServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  3002. // Directory bloccata ?
  3003. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"serverUrl = %@", dirServerUrl]];
  3004. if (directory.lock && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil) lockDirectory = YES;
  3005. NSString *autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  3006. NSString *autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:app.activeUrl];
  3007. [actionSheet addButtonWithTitle: _metadata.fileNamePrint
  3008. image: [CCGraphics changeThemingColorImage:[UIImage imageNamed:_metadata.iconName] color:[NCBrandColor sharedInstance].brand]
  3009. backgroundColor: [NCBrandColor sharedInstance].tabBar
  3010. height: 50.0
  3011. type: AHKActionSheetButtonTypeDisabled
  3012. handler: nil
  3013. ];
  3014. if (!lockDirectory && !_metadata.cryptated) {
  3015. [actionSheet addButtonWithTitle:titleFavorite
  3016. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetFavorite"] color:[NCBrandColor sharedInstance].brand]
  3017. backgroundColor:[UIColor whiteColor]
  3018. height: 50.0
  3019. type:AHKActionSheetButtonTypeDefault
  3020. handler:^(AHKActionSheet *as) {
  3021. // close swipe
  3022. [self setEditing:NO animated:YES];
  3023. if (_metadata.favorite)
  3024. [self removeFavorite:_metadata];
  3025. else
  3026. [self addFavorite:_metadata];
  3027. }];
  3028. }
  3029. if (_metadata.cryptated == NO && !lockDirectory) {
  3030. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  3031. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand]
  3032. backgroundColor:[UIColor whiteColor]
  3033. height: 50.0
  3034. type:AHKActionSheetButtonTypeDefault
  3035. handler:^(AHKActionSheet *as) {
  3036. // close swipe
  3037. [self setEditing:NO animated:YES];
  3038. [self openWindowShare:_metadata];
  3039. }];
  3040. }
  3041. if (!([_metadata.fileName isEqualToString:autoUploadFileName] == YES && [serverUrl isEqualToString:autoUploadDirectory] == YES) && !lockDirectory) {
  3042. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  3043. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRename"] color:[NCBrandColor sharedInstance].brand]
  3044. backgroundColor:[UIColor whiteColor]
  3045. height: 50.0
  3046. type:AHKActionSheetButtonTypeDefault
  3047. handler:^(AHKActionSheet *as) {
  3048. // close swipe
  3049. [self setEditing:NO animated:YES];
  3050. //chiediamo il nome del file
  3051. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_rename_",nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"_cancel_",nil) otherButtonTitles:NSLocalizedString(@"_save_", nil), nil];
  3052. [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
  3053. alertView.tag = alertRename;
  3054. UITextField *textField = [alertView textFieldAtIndex:0];
  3055. textField.text = _metadata.fileNamePrint;
  3056. [alertView show];
  3057. }];
  3058. }
  3059. if (!([_metadata.fileName isEqualToString:autoUploadFileName] == YES && [serverUrl isEqualToString:autoUploadDirectory] == YES) && !lockDirectory) {
  3060. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3061. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetMove"] color:[NCBrandColor sharedInstance].brand]
  3062. backgroundColor:[UIColor whiteColor]
  3063. height: 50.0
  3064. type:AHKActionSheetButtonTypeDefault
  3065. handler:^(AHKActionSheet *as) {
  3066. // close swipe
  3067. [self setEditing:NO animated:YES];
  3068. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3069. }];
  3070. }
  3071. if (!([_metadata.fileName isEqualToString:autoUploadFileName] == YES && [serverUrl isEqualToString:autoUploadDirectory] == YES) && _metadata.cryptated == NO) {
  3072. [actionSheet addButtonWithTitle:NSLocalizedString(@"_folder_automatic_upload_", nil)
  3073. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folderphotocamera"] color:[NCBrandColor sharedInstance].brand]
  3074. backgroundColor:[UIColor whiteColor]
  3075. height: 50.0
  3076. type:AHKActionSheetButtonTypeDefault
  3077. handler:^(AHKActionSheet *as) {
  3078. // close swipe
  3079. [self setEditing:NO animated:YES];
  3080. // Settings new folder Automatatic upload
  3081. NSString *oldAutoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:app.activeUrl];
  3082. [[NCManageDatabase sharedInstance] setAccountAutoUploadFileName:_metadata.fileName];
  3083. [[NCManageDatabase sharedInstance] setAccountAutoUploadDirectory:serverUrl activeUrl:app.activeUrl];
  3084. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:oldAutoUploadDirectory directoryID:nil];
  3085. if (app.activeAccount.length > 0 && app.activePhotos)
  3086. [app.activePhotos reloadDatasourceForced];
  3087. [self readFolderWithForced:YES serverUrl:serverUrl];
  3088. NSLog(@"[LOG] Update Folder Photo");
  3089. NSString *autoUploadPath = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:app.activeUrl];
  3090. if ([autoUploadPath length] > 0)
  3091. [[CCSynchronize sharedSynchronize] readFolderServerUrl:autoUploadPath directoryID:[[NCManageDatabase sharedInstance] getDirectoryID:autoUploadPath] selector:selectorReadFolder];
  3092. }];
  3093. }
  3094. if (!([_metadata.fileName isEqualToString:autoUploadFileName] == YES && [serverUrl isEqualToString:autoUploadDirectory] == YES)) {
  3095. [actionSheet addButtonWithTitle:titoloLock
  3096. image:[UIImage imageNamed:@"actionSheetLock"]
  3097. backgroundColor:[UIColor whiteColor]
  3098. height: 50.0
  3099. type:AHKActionSheetButtonTypeEncrypted
  3100. handler:^(AHKActionSheet *as) {
  3101. // close swipe
  3102. [self setEditing:NO animated:YES];
  3103. [self performSelector:@selector(comandoLockPassword) withObject:nil];
  3104. }];
  3105. }
  3106. if (!([_metadata.fileName isEqualToString:autoUploadFileName] == YES && [serverUrl isEqualToString:autoUploadDirectory] == YES) && !lockDirectory && app.isCryptoCloudMode) {
  3107. [actionSheet addButtonWithTitle:titoloCriptaDecripta
  3108. image:[UIImage imageNamed:@"actionSheetCrypto"]
  3109. backgroundColor:[UIColor whiteColor]
  3110. height: 50.0
  3111. type:AHKActionSheetButtonTypeEncrypted
  3112. handler:^(AHKActionSheet *as) {
  3113. // close swipe
  3114. [self setEditing:NO animated:YES];
  3115. [self performSelector:@selector(encyptedDecryptedFolder) withObject:nil];
  3116. }];
  3117. }
  3118. [actionSheet show];
  3119. }
  3120. /******************************************* FILE *******************************************/
  3121. if ([_metadata.type isEqualToString: k_metadataType_file] && !_metadata.directory) {
  3122. UIImage *iconHeader;
  3123. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  3124. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, _metadata.fileID]])
  3125. iconHeader = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, _metadata.fileID]];
  3126. else
  3127. iconHeader = [UIImage imageNamed:_metadata.iconName];
  3128. [actionSheet addButtonWithTitle: _metadata.fileNamePrint
  3129. image: iconHeader
  3130. backgroundColor: [NCBrandColor sharedInstance].tabBar
  3131. height: 50.0
  3132. type: AHKActionSheetButtonTypeDisabled
  3133. handler: nil
  3134. ];
  3135. if (!_metadata.cryptated) {
  3136. [actionSheet addButtonWithTitle:titleFavorite
  3137. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetFavorite"] color:[NCBrandColor sharedInstance].brand]
  3138. backgroundColor:[UIColor whiteColor]
  3139. height: 50.0
  3140. type:AHKActionSheetButtonTypeDefault
  3141. handler:^(AHKActionSheet *as) {
  3142. // close swipe
  3143. [self setEditing:NO animated:YES];
  3144. if (_metadata.favorite)
  3145. [self removeFavorite:_metadata];
  3146. else
  3147. [self addFavorite:_metadata];
  3148. }];
  3149. }
  3150. if (_metadata.cryptated == NO) {
  3151. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  3152. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand]
  3153. backgroundColor:[UIColor whiteColor]
  3154. height: 50.0
  3155. type:AHKActionSheetButtonTypeDefault
  3156. handler:^(AHKActionSheet *as) {
  3157. // close swipe
  3158. [self setEditing:NO animated:YES];
  3159. [self openWindowShare:_metadata];
  3160. }];
  3161. }
  3162. [actionSheet addButtonWithTitle:NSLocalizedString(@"_open_in_", nil)
  3163. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetOpenIn"] color:[NCBrandColor sharedInstance].brand]
  3164. backgroundColor:[UIColor whiteColor]
  3165. height: 50.0
  3166. type:AHKActionSheetButtonTypeDefault
  3167. handler:^(AHKActionSheet *as) {
  3168. // close swipe
  3169. [self setEditing:NO animated:YES];
  3170. [self performSelector:@selector(openIn:) withObject:_metadata];
  3171. }];
  3172. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  3173. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRename"] color:[NCBrandColor sharedInstance].brand]
  3174. backgroundColor:[UIColor whiteColor]
  3175. height: 50.0
  3176. type:AHKActionSheetButtonTypeDefault
  3177. handler:^(AHKActionSheet *as) {
  3178. // close swipe
  3179. [self setEditing:NO animated:YES];
  3180. //chiediamo il nome del file
  3181. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_rename_",nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"_cancel_",nil) otherButtonTitles:NSLocalizedString(@"_save_", nil), nil];
  3182. [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
  3183. alertView.tag = alertRename;
  3184. UITextField *textField = [alertView textFieldAtIndex:0];
  3185. textField.text = _metadata.fileNamePrint;
  3186. [alertView show];
  3187. }];
  3188. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3189. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetMove"] color:[NCBrandColor sharedInstance].brand]
  3190. backgroundColor:[UIColor whiteColor]
  3191. height: 50.0
  3192. type:AHKActionSheetButtonTypeDefault
  3193. handler:^(AHKActionSheet *as) {
  3194. // close swipe
  3195. [self setEditing:NO animated:YES];
  3196. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3197. }];
  3198. if (localFile || [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, _metadata.fileID]]) {
  3199. [actionSheet addButtonWithTitle:NSLocalizedString(@"_remove_local_file_", nil)
  3200. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRemoveLocal"] color:[NCBrandColor sharedInstance].brand]
  3201. backgroundColor:[UIColor whiteColor]
  3202. height: 50.0
  3203. type:AHKActionSheetButtonTypeDefault
  3204. handler:^(AHKActionSheet *as) {
  3205. // close swipe
  3206. [self setEditing:NO animated:YES];
  3207. [self performSelector:@selector(removeLocalFile:) withObject:_metadata];
  3208. }];
  3209. }
  3210. if (app.isCryptoCloudMode) {
  3211. [actionSheet addButtonWithTitle:titoloCriptaDecripta
  3212. image:[UIImage imageNamed:@"actionSheetCrypto"]
  3213. backgroundColor:[UIColor whiteColor]
  3214. height: 50.0
  3215. type:AHKActionSheetButtonTypeEncrypted
  3216. handler:^(AHKActionSheet *as) {
  3217. // close swipe
  3218. [self setEditing:NO animated:YES];
  3219. [self performSelector:@selector(cmdEncryptedDecryptedFile) withObject:nil];
  3220. }];
  3221. }
  3222. [actionSheet show];
  3223. }
  3224. /******************************************* TEMPLATE *******************************************/
  3225. if ([_metadata.type isEqualToString: k_metadataType_template]) {
  3226. [actionSheet addButtonWithTitle: _metadata.fileNamePrint
  3227. image: [UIImage imageNamed:_metadata.iconName]
  3228. backgroundColor: [NCBrandColor sharedInstance].tabBar
  3229. height: 50.0
  3230. type: AHKActionSheetButtonTypeDisabled
  3231. handler: nil
  3232. ];
  3233. if ([_metadata.model isEqualToString:@"note"]) {
  3234. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  3235. image:[UIImage imageNamed:@"actionSheetRename"]
  3236. backgroundColor:[UIColor whiteColor]
  3237. height: 50.0
  3238. type:AHKActionSheetButtonTypeDefault
  3239. handler:^(AHKActionSheet *as) {
  3240. // close swipe
  3241. [self setEditing:NO animated:YES];
  3242. //chiediamo il nome del file
  3243. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_rename_",nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"_cancel_",nil) otherButtonTitles:NSLocalizedString(@"_save_", nil), nil];
  3244. [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
  3245. alertView.tag = alertRename;
  3246. UITextField *textField = [alertView textFieldAtIndex:0];
  3247. textField.text = _metadata.fileNamePrint;
  3248. [alertView show];
  3249. }];
  3250. }
  3251. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3252. image:[UIImage imageNamed:@"actionSheetMove"]
  3253. backgroundColor:[UIColor whiteColor]
  3254. height: 50.0
  3255. type:AHKActionSheetButtonTypeDefault
  3256. handler:^(AHKActionSheet *as) {
  3257. // close swipe
  3258. [self setEditing:NO animated:YES];
  3259. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3260. }];
  3261. [actionSheet show];
  3262. }
  3263. }
  3264. - (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
  3265. {
  3266. return NSLocalizedString(@"_delete_", nil);
  3267. }
  3268. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
  3269. {
  3270. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3271. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  3272. return NO;
  3273. if (metadata == nil || metadata.errorPasscode || (metadata.cryptated && [metadata.title length] == 0) || metadata.sessionTaskIdentifier >= 0 || metadata.sessionTaskIdentifier >= 0) return NO;
  3274. else return YES;
  3275. }
  3276. - (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
  3277. {
  3278. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  3279. if (_metadata.errorPasscode || (_metadata.cryptated && [_metadata.title length] == 0) || _metadata.sessionTaskIdentifier >= 0 || _metadata.sessionTaskIdentifier >= 0) return UITableViewCellEditingStyleNone;
  3280. else return UITableViewCellEditingStyleDelete;
  3281. }
  3282. - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
  3283. {
  3284. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  3285. BOOL lockDirectory = NO;
  3286. // Directory locked ?
  3287. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:[[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID] addFileName:_metadata.fileNameData];
  3288. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"serverUrl = %@", lockServerUrl]];
  3289. if (directory.lock && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil)
  3290. lockDirectory = YES;
  3291. if (lockDirectory && editingStyle == UITableViewCellEditingStyleDelete) {
  3292. [app messageNotification:@"_error_" description:@"_folder_blocked_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  3293. return;
  3294. }
  3295. if (editingStyle == UITableViewCellEditingStyleDelete) {
  3296. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  3297. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil)
  3298. style:UIAlertActionStyleDestructive
  3299. handler:^(UIAlertAction *action) {
  3300. [self performSelector:@selector(deleteFile) withObject:nil];
  3301. }]];
  3302. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil)
  3303. style:UIAlertActionStyleCancel
  3304. handler:^(UIAlertAction *action) {
  3305. [alertController dismissViewControllerAnimated:YES completion:nil];
  3306. }]];
  3307. alertController.popoverPresentationController.sourceView = self.view;
  3308. alertController.popoverPresentationController.sourceRect = [self.tableView rectForRowAtIndexPath:indexPath];
  3309. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  3310. [alertController.view layoutIfNeeded];
  3311. [self presentViewController:alertController animated:YES completion:nil];
  3312. }
  3313. }
  3314. #pragma --------------------------------------------------------------------------------------------
  3315. #pragma mark - ==== Datasource ====
  3316. #pragma --------------------------------------------------------------------------------------------
  3317. - (void)clearDateReadDataSource:(NSNotification *)notification
  3318. {
  3319. _dateReadDataSource = Nil;
  3320. [self reloadDatasource];
  3321. }
  3322. - (void)reloadDatasource
  3323. {
  3324. [self reloadDatasource:_serverUrl fileID:nil selector:nil];
  3325. }
  3326. - (void)reloadDatasource:(NSString *)serverUrl fileID:(NSString *)fileID selector:(NSString *)selector
  3327. {
  3328. // test
  3329. if (app.activeAccount.length == 0 || serverUrl.length == 0)
  3330. return;
  3331. // Search Mode
  3332. if(_isSearchMode) {
  3333. if ([selector length] == 0 || [selector isEqualToString:selectorSearch]) {
  3334. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:_searchResultMetadatas listProgressMetadata:nil groupByField:_directoryGroupBy replaceDateToExifDate:NO activeAccount:app.activeAccount];
  3335. } else {
  3336. [self readFolderWithForced:NO serverUrl:serverUrl];
  3337. }
  3338. [self tableViewReload];
  3339. if ([_sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] >= k_minCharsSearch) {
  3340. _noFilesSearchTitle = NSLocalizedString(@"_search_no_record_found_", nil);
  3341. _noFilesSearchDescription = @"";
  3342. }
  3343. if ([_sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] < k_minCharsSearch) {
  3344. _noFilesSearchTitle = @"";
  3345. _noFilesSearchDescription = NSLocalizedString(@"_search_instruction_", nil);
  3346. }
  3347. [self.tableView reloadEmptyDataSet];
  3348. return;
  3349. }
  3350. // Reload -> Self se non siamo nella dir appropriata cercala e se è in memoria reindirizza il reload
  3351. if ([serverUrl isEqualToString:_serverUrl] == NO || _serverUrl == nil) {
  3352. if ([selector isEqualToString:selectorDownloadSynchronize]) {
  3353. [app.activeTransfers reloadDatasource];
  3354. } else {
  3355. CCMain *main = [app.listMainVC objectForKey:serverUrl];
  3356. if (main) {
  3357. [main reloadDatasource];
  3358. } else {
  3359. [self tableViewReload];
  3360. [app.activeTransfers reloadDatasource];
  3361. }
  3362. }
  3363. return;
  3364. }
  3365. [app.activeTransfers reloadDatasource];
  3366. // Settaggio variabili per le ottimizzazioni
  3367. _directoryGroupBy = [CCUtility getGroupBySettings];
  3368. _directoryOrder = [CCUtility getOrderSettings];
  3369. // Controllo data lettura Data Source
  3370. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"serverUrl == %@", serverUrl]];
  3371. NSDate *dateDateRecordDirectory = directory.dateReadDirectory;
  3372. if ([dateDateRecordDirectory compare:_dateReadDataSource] == NSOrderedDescending || dateDateRecordDirectory == nil || _dateReadDataSource == nil) {
  3373. NSLog(@"[LOG] Rebuild Data Source File : %@", _serverUrl);
  3374. _dateReadDataSource = [NSDate date];
  3375. // Data Source
  3376. NSArray *recordsTableMetadata = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@", app.activeAccount, [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl]] sorted:[CCUtility getOrderSettings] ascending:[CCUtility getAscendingSettings]];
  3377. _sectionDataSource = [CCSectionDataSourceMetadata new];
  3378. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:recordsTableMetadata listProgressMetadata:nil groupByField:_directoryGroupBy replaceDateToExifDate:NO activeAccount:app.activeAccount];
  3379. } else {
  3380. NSLog(@"[LOG] [OPTIMIZATION] Rebuild Data Source File : %@ - %@", _serverUrl, _dateReadDataSource);
  3381. }
  3382. [self tableViewReload];
  3383. }
  3384. - (NSArray *)getMetadatasFromSelectedRows:(NSArray *)selectedRows
  3385. {
  3386. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  3387. if (selectedRows.count > 0) {
  3388. for (NSIndexPath *selectionIndex in selectedRows) {
  3389. NSString *fileID = [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:selectionIndex.section]] objectAtIndex:selectionIndex.row];
  3390. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3391. [metadatas addObject:metadata];
  3392. }
  3393. }
  3394. return metadatas;
  3395. }
  3396. - (tableMetadata *)getMetadataFromSectionDataSource:(NSIndexPath *)indexPath
  3397. {
  3398. NSInteger section = indexPath.section + 1;
  3399. NSInteger row = indexPath.row + 1;
  3400. NSInteger totSections =[_sectionDataSource.sections count] ;
  3401. if ((totSections < section) || (section > totSections)) {
  3402. NSLog(@"[LOG] %@", [NSString stringWithFormat:@"DEBUG [0] : error section, totSections = %lu - section = %lu", (long)totSections, (long)section]);
  3403. return nil;
  3404. }
  3405. id valueSection = [_sectionDataSource.sections objectAtIndex:indexPath.section];
  3406. NSArray *fileIDs = [_sectionDataSource.sectionArrayRow objectForKey:valueSection];
  3407. if (fileIDs) {
  3408. NSInteger totRows =[fileIDs count] ;
  3409. if ((totRows < row) || (row > totRows)) {
  3410. NSLog(@"[LOG] %@", [NSString stringWithFormat:@"DEBUG [1] : error row, totRows = %lu - row = %lu", (long)totRows, (long)row]);
  3411. return nil;
  3412. }
  3413. } else {
  3414. NSLog(@"[LOG] DEBUG [2] : fileIDs is NIL");
  3415. return nil;
  3416. }
  3417. NSString *fileID = [fileIDs objectAtIndex:indexPath.row];
  3418. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3419. return metadata;
  3420. }
  3421. - (NSArray *)getMetadatasFromSectionDataSource:(NSInteger)section
  3422. {
  3423. NSInteger totSections =[_sectionDataSource.sections count] ;
  3424. if ((totSections < (section + 1)) || ((section + 1) > totSections)) {
  3425. #if DEBUG
  3426. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:[NSString stringWithFormat:@"DEBUG [3] : error section, totSections = %lu - section = %lu", (long)totSections, (long)section] delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  3427. [alertView show];
  3428. #endif
  3429. return nil;
  3430. }
  3431. id valueSection = [_sectionDataSource.sections objectAtIndex:section];
  3432. return [_sectionDataSource.sectionArrayRow objectForKey:valueSection];
  3433. }
  3434. #pragma --------------------------------------------------------------------------------------------
  3435. #pragma mark - ==== Table ====
  3436. #pragma --------------------------------------------------------------------------------------------
  3437. - (void)tableViewSelect:(BOOL)edit
  3438. {
  3439. // chiudiamo eventuali swipe aperti
  3440. if (edit) [self.tableView setEditing:NO animated:NO];
  3441. [self.tableView setAllowsMultipleSelectionDuringEditing:edit];
  3442. [self.tableView setEditing:edit animated:YES];
  3443. _isSelectedMode = edit;
  3444. if (edit)
  3445. [self setUINavigationBarSelected];
  3446. else
  3447. [self setUINavigationBarDefault];
  3448. [self setTitle];
  3449. }
  3450. - (void)tableViewReload
  3451. {
  3452. // ricordiamoci le row selezionate
  3453. NSArray *indexPaths = [self.tableView indexPathsForSelectedRows];
  3454. [self.tableView reloadData];
  3455. for (NSIndexPath *path in indexPaths)
  3456. [self.tableView selectRowAtIndexPath:path animated:NO scrollPosition:UITableViewScrollPositionNone];
  3457. [self setTableViewFooter];
  3458. if (self.tableView.editing)
  3459. [self setTitle];
  3460. }
  3461. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
  3462. {
  3463. return 60;
  3464. }
  3465. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  3466. {
  3467. return [[_sectionDataSource.sectionArrayRow allKeys] count];
  3468. }
  3469. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  3470. {
  3471. return [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:section]] count];
  3472. }
  3473. - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
  3474. {
  3475. NSArray *sections = [_sectionDataSource.sectionArrayRow allKeys];
  3476. NSString *sectionTitle = [sections objectAtIndex:section];
  3477. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"download"].location != NSNotFound) return 18.f;
  3478. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"upload"].location != NSNotFound) return 18.f;
  3479. if ([_directoryGroupBy isEqualToString:@"none"] && [sections count] <= 1) return 0.0f;
  3480. return 20.f;
  3481. }
  3482. -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
  3483. {
  3484. float shift;
  3485. UIVisualEffectView *visualEffectView;
  3486. // Titolo
  3487. NSString *titleSection;
  3488. // Controllo
  3489. if ([_sectionDataSource.sections count] == 0)
  3490. return nil;
  3491. if ([[_sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSString class]]) titleSection = [_sectionDataSource.sections objectAtIndex:section];
  3492. if ([[_sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSDate class]]) titleSection = [CCUtility getTitleSectionDate:[_sectionDataSource.sections objectAtIndex:section]];
  3493. if ([titleSection isEqualToString:@"_none_"]) titleSection = @"";
  3494. else if ([titleSection rangeOfString:@"download"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_download_",nil);
  3495. else if ([titleSection rangeOfString:@"upload"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_upload_",nil);
  3496. else titleSection = NSLocalizedString(titleSection,nil);
  3497. // Formato titolo
  3498. NSString *currentDevice = [CCUtility currentDevice];
  3499. if ([currentDevice rangeOfString:@"iPad3"].location != NSNotFound) {
  3500. visualEffectView = [[UIVisualEffectView alloc] init];
  3501. visualEffectView.backgroundColor = [[NCBrandColor sharedInstance].brand colorWithAlphaComponent:0.3];
  3502. } else {
  3503. UIVisualEffect *blurEffect;
  3504. blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
  3505. visualEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
  3506. visualEffectView.backgroundColor = [[NCBrandColor sharedInstance].brand colorWithAlphaComponent:0.2];
  3507. }
  3508. if ([_directoryGroupBy isEqualToString:@"alphabetic"]) {
  3509. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) shift = - 35;
  3510. else shift = - 20;
  3511. } else shift = - 10;
  3512. // Title
  3513. UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, -12, 0, 44)];
  3514. titleLabel.backgroundColor = [UIColor clearColor];
  3515. titleLabel.textColor = [UIColor blackColor];
  3516. titleLabel.font = [UIFont systemFontOfSize:12];
  3517. titleLabel.textAlignment = NSTextAlignmentLeft;
  3518. titleLabel.text = titleSection;
  3519. titleLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3520. [visualEffectView addSubview:titleLabel];
  3521. // Elements
  3522. UILabel *elementLabel= [[UILabel alloc]initWithFrame:CGRectMake(shift, -12, 0, 44)];
  3523. elementLabel.backgroundColor = [UIColor clearColor];
  3524. elementLabel.textColor = [UIColor blackColor];;
  3525. elementLabel.font = [UIFont systemFontOfSize:12];
  3526. elementLabel.textAlignment = NSTextAlignmentRight;
  3527. elementLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3528. NSArray *metadatas = [self getMetadatasFromSectionDataSource:section];
  3529. NSUInteger rowsCount = [metadatas count];
  3530. if (rowsCount == 0) return nil;
  3531. if (rowsCount == 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_element_",nil)];
  3532. if (rowsCount > 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_elements_",nil)];
  3533. [visualEffectView addSubview:elementLabel];
  3534. return visualEffectView;
  3535. }
  3536. - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
  3537. {
  3538. return [_sectionDataSource.sections indexOfObject:title];
  3539. }
  3540. - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
  3541. {
  3542. if ([_directoryGroupBy isEqualToString:@"alphabetic"])
  3543. return [[UILocalizedIndexedCollation currentCollation] sectionIndexTitles];
  3544. else
  3545. return nil;
  3546. }
  3547. /*
  3548. -(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  3549. {
  3550. if([indexPath row] == ((NSIndexPath*)[[tableView indexPathsForVisibleRows] lastObject]).row){
  3551. }
  3552. }
  3553. */
  3554. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  3555. {
  3556. NSString *typeCell;
  3557. NSString *dataFile;
  3558. NSString *lunghezzaFile;
  3559. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3560. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata]) {
  3561. return [tableView dequeueReusableCellWithIdentifier:@"CellMainTransfer"];
  3562. }
  3563. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  3564. if ([metadata.session isEqualToString:@""] || metadata.session == nil) typeCell = @"CellMain";
  3565. else typeCell = @"CellMainTransfer";
  3566. CCCellMainTransfer *cell = (CCCellMainTransfer *)[tableView dequeueReusableCellWithIdentifier:typeCell forIndexPath:indexPath];
  3567. // separator
  3568. cell.separatorInset = UIEdgeInsetsMake(0.f, 60.f, 0.f, 0.f);
  3569. // change color selection
  3570. UIView *selectionColor = [[UIView alloc] init];
  3571. selectionColor.backgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  3572. cell.selectedBackgroundView = selectionColor;
  3573. if ([typeCell isEqualToString:@"CellMain"]) cell.backgroundColor = [UIColor whiteColor];
  3574. if ([typeCell isEqualToString:@"CellMainTransfer"]) cell.backgroundColor = [NCBrandColor sharedInstance].transferBackground;
  3575. // ----------------------------------------------------------------------------------------------------------
  3576. // DEFAULT
  3577. // ----------------------------------------------------------------------------------------------------------
  3578. cell.fileImageView.image = nil;
  3579. cell.statusImageView.image = nil;
  3580. cell.offlineImageView.image = nil;
  3581. cell.synchronizedImageView.image = nil;
  3582. cell.sharedImageView.image = nil;
  3583. cell.labelTitle.enabled = YES;
  3584. cell.labelTitle.text = @"";
  3585. cell.labelInfoFile.enabled = YES;
  3586. cell.labelInfoFile.text = @"";
  3587. cell.progressView.progress = 0.0;
  3588. cell.progressView.hidden = YES;
  3589. cell.cancelTaskButton.hidden = YES;
  3590. cell.reloadTaskButton.hidden = YES;
  3591. cell.stopTaskButton.hidden = YES;
  3592. // Encrypted color
  3593. if (metadata.cryptated) {
  3594. cell.labelTitle.textColor = [NCBrandColor sharedInstance].cryptocloud;
  3595. } else {
  3596. cell.labelTitle.textColor = [UIColor blackColor];
  3597. }
  3598. // ----------------------------------------------------------------------------------------------------------
  3599. // File Name & Folder
  3600. // ----------------------------------------------------------------------------------------------------------
  3601. // nome del file
  3602. cell.labelTitle.text = metadata.fileNamePrint;
  3603. // è una directory
  3604. if (metadata.directory) {
  3605. cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
  3606. cell.labelInfoFile.text = [CCUtility dateDiff:metadata.date];
  3607. lunghezzaFile = @" ";
  3608. // ----------------------------------------------------------------------------------------------------------
  3609. // Favorite Folder
  3610. // ----------------------------------------------------------------------------------------------------------
  3611. if (metadata.favorite) {
  3612. cell.offlineImageView.image = [UIImage imageNamed:@"favorite"];
  3613. }
  3614. } else {
  3615. // File
  3616. dataFile = [CCUtility dateDiff:metadata.date];
  3617. lunghezzaFile = [CCUtility transformedSize:metadata.size];
  3618. // Plist ancora da scaricare
  3619. if (metadata.cryptated && [metadata.title length] == 0) {
  3620. dataFile = @" ";
  3621. lunghezzaFile = @" ";
  3622. }
  3623. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadata.fileID]];
  3624. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  3625. [dateFormatter setDateStyle:NSDateFormatterShortStyle];
  3626. [dateFormatter setTimeStyle:NSDateFormatterShortStyle];
  3627. if ([metadata.type isEqualToString: k_metadataType_template] && [dataFile isEqualToString:@" "] == NO && [lunghezzaFile isEqualToString:@" "] == NO)
  3628. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", dataFile];
  3629. if ([metadata.type isEqualToString: k_metadataType_file] && [dataFile isEqualToString:@" "] == NO && [lunghezzaFile isEqualToString:@" "] == NO) {
  3630. if (localFile && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID]])
  3631. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@ • %@", dataFile, lunghezzaFile];
  3632. else
  3633. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@ ◦ %@", dataFile, lunghezzaFile];
  3634. }
  3635. // Plist ancora da scaricare
  3636. if ([dataFile isEqualToString:@" "] && [lunghezzaFile isEqualToString:@" "])
  3637. cell.labelInfoFile.text = NSLocalizedString(@"_no_plist_pull_down_",nil);
  3638. cell.accessoryType = UITableViewCellAccessoryNone;
  3639. }
  3640. // ----------------------------------------------------------------------------------------------------------
  3641. // File Image View
  3642. // ----------------------------------------------------------------------------------------------------------
  3643. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  3644. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]]) {
  3645. cell.fileImageView.image = [app.icoImagesCache objectForKey:metadata.fileID];
  3646. if (cell.fileImageView.image == nil) {
  3647. NSString *fileID = metadata.fileID;
  3648. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  3649. UIImage *image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, fileID]];
  3650. [app.icoImagesCache setObject:image forKey:fileID];
  3651. dispatch_async(dispatch_get_main_queue(), ^{
  3652. CCCellMainTransfer *cell = [tableView cellForRowAtIndexPath:indexPath];
  3653. if (cell)
  3654. cell.fileImageView.image = image;
  3655. });
  3656. });
  3657. }
  3658. } else {
  3659. if (metadata.directory)
  3660. cell.fileImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:metadata.iconName] color:[NCBrandColor sharedInstance].brand];
  3661. else
  3662. cell.fileImageView.image = [UIImage imageNamed:metadata.iconName];
  3663. if (metadata.thumbnailExists)
  3664. [[CCActions sharedInstance] downloadTumbnail:metadata delegate:self];
  3665. }
  3666. // ----------------------------------------------------------------------------------------------------------
  3667. // Image Status cyptated & Lock Passcode
  3668. // ----------------------------------------------------------------------------------------------------------
  3669. // File Cyptated
  3670. if (metadata.cryptated && metadata.directory == NO && [metadata.type isEqualToString: k_metadataType_template] == NO) {
  3671. cell.statusImageView.image = [UIImage imageNamed:@"lock"];
  3672. }
  3673. // Directory con passcode lock attivato
  3674. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:metadata.fileNameData];
  3675. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"serverUrl = %@", lockServerUrl]];
  3676. if (metadata.directory && (directory.lock && [[CCUtility getBlockCode] length]))
  3677. cell.statusImageView.image = [UIImage imageNamed:@"passcode"];
  3678. // ----------------------------------------------------------------------------------------------------------
  3679. // Favorite
  3680. // ----------------------------------------------------------------------------------------------------------
  3681. if (metadata.favorite) {
  3682. cell.offlineImageView.image = [UIImage imageNamed:@"favorite"];
  3683. }
  3684. // ----------------------------------------------------------------------------------------------------------
  3685. // Share
  3686. // ----------------------------------------------------------------------------------------------------------
  3687. NSString *shareLink = [app.sharesLink objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3688. NSString *shareUserAndGroup = [app.sharesUserAndGroup objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3689. BOOL isShare = ([metadata.permissions length] > 0) && ([metadata.permissions rangeOfString:k_permission_shared].location != NSNotFound) && ([_fatherPermission rangeOfString:k_permission_shared].location == NSNotFound);
  3690. BOOL isMounted = ([metadata.permissions length] > 0) && ([metadata.permissions rangeOfString:k_permission_mounted].location != NSNotFound) && ([_fatherPermission rangeOfString:k_permission_mounted].location == NSNotFound);
  3691. // Aggiungiamo il Tap per le shared
  3692. if (isShare || [shareLink length] > 0 || [shareUserAndGroup length] > 0 || isMounted) {
  3693. if (isShare) {
  3694. if (metadata.directory) {
  3695. cell.fileImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_shared_with_me"] color:[NCBrandColor sharedInstance].brand];
  3696. cell.sharedImageView.userInteractionEnabled = NO;
  3697. } else {
  3698. cell.sharedImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand];
  3699. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionConnectionMounted:)];
  3700. [tap setNumberOfTapsRequired:1];
  3701. cell.sharedImageView.userInteractionEnabled = YES;
  3702. [cell.sharedImageView addGestureRecognizer:tap];
  3703. }
  3704. }
  3705. if (isMounted) {
  3706. if (metadata.directory) {
  3707. cell.fileImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_external"] color:[NCBrandColor sharedInstance].brand];
  3708. cell.sharedImageView.userInteractionEnabled = NO;
  3709. } else {
  3710. cell.sharedImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"shareMounted"] color:[NCBrandColor sharedInstance].brand];
  3711. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionConnectionMounted:)];
  3712. [tap setNumberOfTapsRequired:1];
  3713. cell.sharedImageView.userInteractionEnabled = YES;
  3714. [cell.sharedImageView addGestureRecognizer:tap];
  3715. }
  3716. }
  3717. if ([shareLink length] > 0 || [shareUserAndGroup length] > 0) {
  3718. if (metadata.directory) {
  3719. if ([shareLink length] > 0)
  3720. cell.fileImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_public"] color:[NCBrandColor sharedInstance].brand];
  3721. if ([shareUserAndGroup length] > 0)
  3722. cell.fileImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_shared_with_me"] color:[NCBrandColor sharedInstance].brand];
  3723. cell.sharedImageView.userInteractionEnabled = NO;
  3724. } else {
  3725. if ([shareLink length] > 0)
  3726. cell.sharedImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"shareLink"] color:[NCBrandColor sharedInstance].brand];
  3727. if ([shareUserAndGroup length] > 0)
  3728. cell.sharedImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand];
  3729. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionShared:)];
  3730. [tap setNumberOfTapsRequired:1];
  3731. cell.sharedImageView.userInteractionEnabled = YES;
  3732. [cell.sharedImageView addGestureRecognizer:tap];
  3733. }
  3734. }
  3735. } else {
  3736. cell.sharedImageView.userInteractionEnabled = NO;
  3737. }
  3738. // ----------------------------------------------------------------------------------------------------------
  3739. // downloadFile
  3740. // ----------------------------------------------------------------------------------------------------------
  3741. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  3742. if (metadata.cryptated) cell.statusImageView.image = [UIImage imageNamed:@"statusdownloadcrypto"];
  3743. else cell.statusImageView.image = [UIImage imageNamed:@"statusdownload"];
  3744. // sessionTaskIdentifier : RELOAD + STOP
  3745. if (metadata.sessionTaskIdentifier != k_taskIdentifierDone) {
  3746. if (metadata.cryptated)[cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptaskcrypto"] forState:UIControlStateNormal];
  3747. else [cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptask"] forState:UIControlStateNormal];
  3748. cell.cancelTaskButton.hidden = NO;
  3749. if (metadata.cryptated)[cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtaskcrypto"] forState:UIControlStateNormal];
  3750. else [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtask"] forState:UIControlStateNormal];
  3751. cell.reloadTaskButton.hidden = NO;
  3752. }
  3753. // sessionTaskIdentifierPlist : RELOAD
  3754. if (metadata.sessionTaskIdentifierPlist != k_taskIdentifierDone) {
  3755. if (metadata.cryptated)[cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtaskcrypto"] forState:UIControlStateNormal];
  3756. else [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtask"] forState:UIControlStateNormal];
  3757. cell.reloadTaskButton.hidden = NO;
  3758. }
  3759. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", lunghezzaFile];
  3760. float progress = [[app.listProgressMetadata objectForKey:metadata.fileID] floatValue];
  3761. if (progress > 0) {
  3762. if (metadata.cryptated) cell.progressView.progressTintColor = [NCBrandColor sharedInstance].cryptocloud;
  3763. else cell.progressView.progressTintColor = [UIColor blackColor];
  3764. cell.progressView.progress = progress;
  3765. cell.progressView.hidden = NO;
  3766. }
  3767. // ----------------------------------------------------------------------------------------------------------
  3768. // downloadFile Error
  3769. // ----------------------------------------------------------------------------------------------------------
  3770. if (metadata.sessionTaskIdentifier == k_taskIdentifierError || metadata.sessionTaskIdentifierPlist == k_taskIdentifierError) {
  3771. cell.statusImageView.image = [UIImage imageNamed:@"statuserror"];
  3772. if ([metadata.sessionError length] == 0)
  3773. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@, %@", NSLocalizedString(@"_error_",nil), NSLocalizedString(@"_file_not_downloaded_",nil)];
  3774. else
  3775. cell.labelInfoFile.text = [CCError manageErrorKCF:[metadata.sessionError integerValue] withNumberError:NO];
  3776. }
  3777. }
  3778. // ----------------------------------------------------------------------------------------------------------
  3779. // uploadFile
  3780. // ----------------------------------------------------------------------------------------------------------
  3781. if ([metadata.session length] > 0 && [metadata.session rangeOfString:@"upload"].location != NSNotFound) {
  3782. if (metadata.cryptated) cell.statusImageView.image = [UIImage imageNamed:@"statusuploadcrypto"];
  3783. else cell.statusImageView.image = [UIImage imageNamed:@"statusupload"];
  3784. if (metadata.cryptated)[cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"removetaskcrypto"] forState:UIControlStateNormal];
  3785. else [cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"removetask"] forState:UIControlStateNormal];
  3786. cell.cancelTaskButton.hidden = NO;
  3787. if (metadata.sessionTaskIdentifier == k_taskIdentifierStop) {
  3788. if (metadata.cryptated)[cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtaskcrypto"] forState:UIControlStateNormal];
  3789. else [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtask"] forState:UIControlStateNormal];
  3790. if (metadata.cryptated) cell.statusImageView.image = [UIImage imageNamed:@"statusstopcrypto"];
  3791. else cell.statusImageView.image = [UIImage imageNamed:@"statusstop"];
  3792. cell.reloadTaskButton.hidden = NO;
  3793. cell.stopTaskButton.hidden = YES;
  3794. } else {
  3795. if (metadata.cryptated)[cell.stopTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptaskcrypto"] forState:UIControlStateNormal];
  3796. else [cell.stopTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptask"] forState:UIControlStateNormal];
  3797. cell.stopTaskButton.hidden = NO;
  3798. cell.reloadTaskButton.hidden = YES;
  3799. }
  3800. // se non c'è una preview in bianconero metti l'immagine di default
  3801. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]] == NO)
  3802. cell.fileImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"uploaddisable"] color:[NCBrandColor sharedInstance].brand];
  3803. cell.labelTitle.enabled = NO;
  3804. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", lunghezzaFile];
  3805. float progress = [[app.listProgressMetadata objectForKey:metadata.fileID] floatValue];
  3806. if (progress > 0) {
  3807. if (metadata.cryptated) cell.progressView.progressTintColor = [NCBrandColor sharedInstance].cryptocloud;
  3808. else cell.progressView.progressTintColor = [UIColor blackColor];
  3809. cell.progressView.progress = progress;
  3810. cell.progressView.hidden = NO;
  3811. }
  3812. // ----------------------------------------------------------------------------------------------------------
  3813. // uploadFileError
  3814. // ----------------------------------------------------------------------------------------------------------
  3815. if (metadata.sessionTaskIdentifier == k_taskIdentifierError || metadata.sessionTaskIdentifierPlist == k_taskIdentifierError) {
  3816. cell.labelTitle.enabled = NO;
  3817. cell.statusImageView.image = [UIImage imageNamed:@"statuserror"];
  3818. if ([metadata.sessionError length] == 0)
  3819. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@, %@", NSLocalizedString(@"_error_",nil), NSLocalizedString(@"_file_not_uploaded_",nil)];
  3820. else
  3821. cell.labelInfoFile.text = [CCError manageErrorKCF:[metadata.sessionError integerValue] withNumberError:NO];
  3822. }
  3823. }
  3824. [cell.reloadTaskButton addTarget:self action:@selector(reloadTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3825. [cell.cancelTaskButton addTarget:self action:@selector(cancelTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3826. [cell.stopTaskButton addTarget:self action:@selector(stopTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3827. return cell;
  3828. }
  3829. - (void)setTableViewFooter
  3830. {
  3831. UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3832. [footerView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3833. UILabel *footerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3834. [footerLabel setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3835. UIFont *appFont = [UIFont systemFontOfSize:12];
  3836. footerLabel.font = appFont;
  3837. footerLabel.textColor = [UIColor grayColor];
  3838. footerLabel.backgroundColor = [UIColor clearColor];
  3839. footerLabel.textAlignment = NSTextAlignmentCenter;
  3840. NSString *folders;
  3841. NSString *files;
  3842. NSString *footerText;
  3843. if (_sectionDataSource.directories > 1) {
  3844. folders = [NSString stringWithFormat:@"%ld %@", (long)_sectionDataSource.directories, NSLocalizedString(@"_folders_", nil)];
  3845. } else if (_sectionDataSource.directories == 1){
  3846. folders = [NSString stringWithFormat:@"%ld %@", (long)_sectionDataSource.directories, NSLocalizedString(@"_folder_", nil)];
  3847. } else {
  3848. folders = @"";
  3849. }
  3850. if (_sectionDataSource.files > 1) {
  3851. files = [NSString stringWithFormat:@"%ld %@ %@", (long)_sectionDataSource.files, NSLocalizedString(@"_files_", nil), [CCUtility transformedSize:_sectionDataSource.totalSize]];
  3852. } else if (_sectionDataSource.files == 1){
  3853. files = [NSString stringWithFormat:@"%ld %@ %@", (long)_sectionDataSource.files, NSLocalizedString(@"_file_", nil), [CCUtility transformedSize:_sectionDataSource.totalSize]];
  3854. } else {
  3855. files = @"";
  3856. }
  3857. if ([folders isEqualToString:@""]) {
  3858. footerText = files;
  3859. } else if ([files isEqualToString:@""]) {
  3860. footerText = folders;
  3861. } else {
  3862. footerText = [NSString stringWithFormat:@"%@, %@", folders, files];
  3863. }
  3864. footerLabel.text = footerText;
  3865. [footerView addSubview:footerLabel];
  3866. [self.tableView setTableFooterView:footerView];
  3867. }
  3868. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  3869. {
  3870. NSString *textMessage;
  3871. UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
  3872. // settiamo il record file.
  3873. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  3874. // se non può essere selezionata deseleziona
  3875. if ([cell isEditing] == NO)
  3876. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  3877. // se siamo in modalità editing impostiamo il titolo dei selezioati e usciamo subito
  3878. if (self.tableView.editing) {
  3879. [self setTitle];
  3880. return;
  3881. }
  3882. // test crash
  3883. NSArray *metadatas = [_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:indexPath.section]];
  3884. if (indexPath.row >= [metadatas count]) return;
  3885. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  3886. // se è in corso una sessione
  3887. if ([_metadata.session length] > 0) return;
  3888. if (_metadata.errorPasscode) {
  3889. // se UUID è nil lo sta ancora caricando quindi esci
  3890. if (!_metadata.uuid) return;
  3891. // esiste un hint ??
  3892. NSString *hint = [[CCCrypto sharedManager] getHintFromFile:_metadata.fileName isLocal:NO directoryUser:app.directoryUser];
  3893. // qui !! la richiesta della nuova passcode
  3894. if ([_metadata.uuid isEqualToString:[CCUtility getUUID]]) {
  3895. // stesso UUID ... la password è stata modificata !!!!!!
  3896. if (hint) textMessage = [NSString stringWithFormat:NSLocalizedString(@"_same_device_different_passcode_hint_",nil), hint];
  3897. else textMessage = NSLocalizedString(@"_same_device_different_passcode_", nil);
  3898. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:textMessage delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  3899. [alertView show];
  3900. } else {
  3901. // UUID diverso.
  3902. if (hint) textMessage = [NSString stringWithFormat:NSLocalizedString(@"_file_encrypted_another_device_hint_",nil), _metadata.nameCurrentDevice, hint];
  3903. else textMessage = [NSString stringWithFormat:NSLocalizedString(@"_file_encrypted_another_device_",nil), _metadata.nameCurrentDevice];
  3904. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:textMessage delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  3905. [alertView show];
  3906. }
  3907. // chiediamo la passcode e ricarichiamo tutto.
  3908. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  3909. viewController.delegate = self;
  3910. viewController.fromType = CCBKPasscodeFromPasscode;
  3911. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  3912. viewController.passcodeInputView.maximumLength = 64;
  3913. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  3914. viewController.inputViewTitlePassword = NO;
  3915. viewController.title = [NCBrandOptions sharedInstance].brand;
  3916. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  3917. viewController.navigationItem.leftBarButtonItem.tintColor = [NCBrandColor sharedInstance].cryptocloud;
  3918. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  3919. [self presentViewController:navigationController animated:YES completion:nil];
  3920. }
  3921. // modello o plist con il title a 0 allora è andato storto qualcosa ... ricaricalo
  3922. if (_metadata.cryptated && [_metadata.title length] == 0) {
  3923. NSString* selector;
  3924. if ([_metadata.type isEqualToString: k_metadataType_template]) selector = selectorLoadModelView;
  3925. else selector = selectorLoadPlist;
  3926. [[CCNetworking sharedNetworking] downloadFile:_metadata.fileID serverUrl:serverUrl downloadData:NO downloadPlist:YES selector:selector selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  3927. return;
  3928. }
  3929. // se il plist è caricato ed è un modello aprilo
  3930. if ([_metadata.type isEqualToString:k_metadataType_template]) [self openModel:_metadata.model isNew:false];
  3931. // file
  3932. if (_metadata.directory == NO && _metadata.errorPasscode == NO && [_metadata.type isEqualToString: k_metadataType_file]) {
  3933. // se il file esiste andiamo direttamente al delegato altrimenti carichiamolo
  3934. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, _metadata.fileID]]) {
  3935. [self downloadFileSuccess:_metadata.fileID serverUrl:serverUrl selector:selectorLoadFileView selectorPost:nil];
  3936. } else {
  3937. [[CCNetworking sharedNetworking] downloadFile:_metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorLoadFileView selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  3938. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:_metadata.fileID];
  3939. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  3940. }
  3941. }
  3942. if (_metadata.directory) [self performSegueDirectoryWithControlPasscode:true];
  3943. }
  3944. - (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
  3945. {
  3946. [self setTitle];
  3947. }
  3948. #pragma --------------------------------------------------------------------------------------------
  3949. #pragma mark ===== Synchronize Folder Cell =====
  3950. #pragma --------------------------------------------------------------------------------------------
  3951. - (void)synchronizeFolderGraphicsServerUrl:(NSString *)serverUrl animation:(BOOL)animation
  3952. {
  3953. BOOL cryptated = NO;
  3954. CCCellMain *cell;
  3955. for (NSString* fileID in _sectionDataSource.allRecordsDataSource) {
  3956. tableMetadata *recordMetadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3957. if (recordMetadata.directory == NO)
  3958. continue;
  3959. if ([[CCUtility stringAppendServerUrl:_serverUrl addFileName:recordMetadata.fileNameData] isEqualToString:serverUrl]) {
  3960. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:recordMetadata.fileID];
  3961. cell = (CCCellMain *)[self.tableView cellForRowAtIndexPath:indexPath];
  3962. cryptated = recordMetadata.cryptated;
  3963. break;
  3964. }
  3965. }
  3966. if (!cell)
  3967. return;
  3968. if (animation) {
  3969. NSURL *myURL;
  3970. if (cryptated)
  3971. myURL = [[NSBundle mainBundle] URLForResource: @"synchronizedcrypto" withExtension:@"gif"];
  3972. else
  3973. myURL = [[NSBundle mainBundle] URLForResource: @"synchronized" withExtension:@"gif"];
  3974. } else {
  3975. cell.synchronizedImageView.image = nil;
  3976. }
  3977. }
  3978. #pragma --------------------------------------------------------------------------------------------
  3979. #pragma mark ===== Navigation ====
  3980. #pragma --------------------------------------------------------------------------------------------
  3981. - (BOOL)shouldPerformSegue
  3982. {
  3983. // if background return
  3984. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) return NO;
  3985. if (self.view.window == NO)
  3986. return NO;
  3987. // Collapsed ma siamo già in detail esci
  3988. if (self.splitViewController.isCollapsed)
  3989. if (_detailViewController.isViewLoaded && _detailViewController.view.window) return NO;
  3990. // Video in esecuzione esci
  3991. if (_detailViewController.photoBrowser.currentVideoPlayerViewController.isViewLoaded && _detailViewController.photoBrowser.currentVideoPlayerViewController.view.window) return NO;
  3992. return YES;
  3993. }
  3994. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
  3995. {
  3996. id viewController = segue.destinationViewController;
  3997. NSMutableArray *allRecordsDataSourceImagesVideos = [NSMutableArray new];
  3998. tableMetadata *metadata;
  3999. if ([viewController isKindOfClass:[UINavigationController class]]) {
  4000. UINavigationController *nav = viewController;
  4001. _detailViewController = (CCDetail *)nav.topViewController;
  4002. } else {
  4003. _detailViewController = segue.destinationViewController;
  4004. }
  4005. if ([sender isKindOfClass:[tableMetadata class]]) {
  4006. metadata = sender;
  4007. [allRecordsDataSourceImagesVideos addObject:sender];
  4008. } else {
  4009. metadata = _metadata;
  4010. for (NSString *fileID in _sectionDataSource.allEtag) {
  4011. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  4012. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])
  4013. [allRecordsDataSourceImagesVideos addObject:metadata];
  4014. }
  4015. }
  4016. _detailViewController.metadataDetail = metadata;
  4017. _detailViewController.dataSourceImagesVideos = allRecordsDataSourceImagesVideos;
  4018. _detailViewController.dateFilterQuery = nil;
  4019. [_detailViewController setTitle:metadata.fileNamePrint];
  4020. }
  4021. // can i go to next viewcontroller
  4022. - (void)performSegueDirectoryWithControlPasscode:(BOOL)controlPasscode
  4023. {
  4024. NSString *nomeDir;
  4025. if(self.tableView.editing == NO && _metadata.errorPasscode == NO){
  4026. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  4027. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  4028. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"serverUrl = %@", lockServerUrl]];
  4029. // SE siamo in presenza di una directory bloccata E è attivo il block E la sessione password Lock è senza data ALLORA chiediamo la password per procedere
  4030. if (directory.lock && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil && controlPasscode) {
  4031. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  4032. viewController.delegate = self;
  4033. viewController.fromType = CCBKPasscodeFromLockDirectory;
  4034. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  4035. viewController.inputViewTitlePassword = YES;
  4036. if ([CCUtility getSimplyBlockCode]) {
  4037. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  4038. viewController.passcodeInputView.maximumLength = 6;
  4039. } else {
  4040. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  4041. viewController.passcodeInputView.maximumLength = 64;
  4042. }
  4043. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  4044. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  4045. viewController.touchIDManager = touchIDManager;
  4046. viewController.title = NSLocalizedString(@"_folder_blocked_", nil);
  4047. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  4048. viewController.navigationItem.leftBarButtonItem.tintColor = [NCBrandColor sharedInstance].cryptocloud;
  4049. UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];
  4050. [self presentViewController:navController animated:YES completion:nil];
  4051. return;
  4052. }
  4053. if (_metadata.cryptated) nomeDir = [_metadata.fileName substringToIndex:[_metadata.fileName length]-6];
  4054. else nomeDir = _metadata.fileName;
  4055. NSString *serverUrlPush = [CCUtility stringAppendServerUrl:serverUrl addFileName:nomeDir];
  4056. CCMain *viewController = [app.listMainVC objectForKey:serverUrlPush];
  4057. if (viewController.isViewLoaded == false || viewController == nil) {
  4058. viewController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMainVC"];
  4059. viewController.isFolderEncrypted = _metadata.cryptated;
  4060. viewController.serverUrl = serverUrlPush;
  4061. viewController.titleMain = _metadata.fileNamePrint;
  4062. viewController.textBackButton = _titleMain;
  4063. // save self
  4064. [app.listMainVC setObject:viewController forKey:serverUrlPush];
  4065. }
  4066. // OFF SearchBar
  4067. [viewController cancelSearchBar];
  4068. [self.navigationController pushViewController:viewController animated:YES];
  4069. }
  4070. }
  4071. @end