CCMain.m 250 KB

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